打印函数后跟中断函数不返回任何内容


from random import randint
goal = randint(1,2)
guess = int(input('guess a number from 1 to 2'))
while (goal != guess):
if(guess > goal):
print('too high')
guess = int(input('guess a number from 1 to 2'))
elif(guess < goal):
print('too low')
guess = int(input('guess a number from 1 to 2'))
elif(guess == goal):
print('☺')
break

这是我的代码,我不知道为什么解释器和控制台什么都不返回。

guess a number from 1 to 2. 2
too high
guess a number from 1 to 2. 1
>>> 

我真的不知道该怎么办。 提前谢谢。

编辑:非常感谢大家!这真的很有帮助。谢谢

您的while循环条件在您的elif guess == goal有机会看到相等之前退出循环。每次您提供新输入时,它总是在达到elif guess == goal:之前由while goal != guess:进行测试。

要解决此问题,您可以将while设置为无限循环:

while True:  # Never exit here, so final case is responsible for printing/breaking
if guess > goal:
print('too high')
guess = int(input('guess a number from 1 to 2'))
elif guess < goal:
print('too low')
guess = int(input('guess a number from 1 to 2'))
else:  # No need for elif at all; for ints, not being greater or less than implies equal
print('☺')
break

或者将最终elif的主体移出while循环:

while goal != guess:
if guess > goal:
print('too high')
guess = int(input('guess a number from 1 to 2'))
elif guess < goal:
print('too low')
guess = int(input('guess a number from 1 to 2'))
print('☺')  # If we got here, goal must be equal to guess

在这两种情况下,我都稍微修复了样式以匹配 PEP8(您不需要括号是 Python 中while/if的条件测试(。

实际上,为了最大程度地减少代码重复,您需要将input移动到循环的顶部,并且仅在底部中断,从而使您的代码如下所示:

goal = randint(1,2)
while True:
guess = int(input('guess a number from 1 to 2'))
if guess > goal:
print('too high')
elif guess < goal:
print('too low')
else:
print('☺')
break

或者使用 Python 3.8+ 的赋值表达式来允许在条件中进行设置和测试,您可以通过以下方式使其更简洁(尽管可能更晦涩

(:
goal = randint(1,2)
while goal != (guess := int(input('guess a number from 1 to 2'))):
if guess > goal:
print('too high')
else:
print('too low')
print('☺')  # If we got here, goal must be equal to guess

所以我会试着形成我的答案,以便你可以跟上。

while (goal != guess):

是罪魁祸首。这在每个循环上运行。因此,一旦它是真的,它将在不检查最后一句话的情况下突破循环以打印笑脸。因此,一种解决方案可能是执行以下操作:

from random import randint
goal = randint(1,2)
guess = int(input('guess a number from 1 to 2'))
guessed = False
while not guessed:
if(guess > goal):
print('too high')
guess = int(input('guess a number from 1 to 2'))
elif(guess < goal):
print('too low')
guess = int(input('guess a number from 1 to 2'))
elif(guess == goal):
print('☺')
guessed = True

希望这对您有所帮助。

将猜测放在循环的顶部,而不是在每个条件中。这使您可以知道哪一行被激活,易于更新,并且您不会重复代码。

low, high = 1, 2
goal = randint(low, high)
while True:
guess = int(input(f'guess a number from {low} to {high}: '))
if(guess > goal):
print('too high')
elif(guess < goal):
print('too low')
elif(guess == goal):
print('Success!')
break

最新更新