所以,我有这个程序,你必须猜测一个数字,我已编码,以便程序会告诉你你猜对的数字是高于还是低于真实数字。我的问题是程序在告诉用户猜测更高或更低之后结束。我希望程序循环,以便程序不会结束,直到我预设的数字被猜到。这是我的代码:
number = 10
guess = int(input("Type in an integer: "))
if guess == number:
print ("Good Job!")
elif guess < number:
print ("The number is higher")
else:
print ("The number is lower")
while guess!= number:
print ("Try Again")
print ("Done")
我尝试使用while循环来循环程序,直到数字被正确猜到,但是&#34;再试一次&#34;脚本永远循环......谢谢你的帮助!
答案 0 :(得分:3)
您的流量控件设计不当,但您可以通过将代码包装在while
循环中,然后应用break
guess == number
来解决问题。 guess!=number
的其他情况,循环一直在运行:
number = 10
while True:
guess = int(input("Type in an integer: "))
if guess == number:
print ("Good Job!")
break
elif guess < number:
print ("The number is higher")
else:
print ("The number is lower")
print ("Done")
您可以在python here
中阅读有关while
循环的更多信息
答案 1 :(得分:2)
while
循环不起作用。看起来你期待某种goto
,它猜测你希望它重复什么,但它重复的是块的内容。如果它到达while guess != number:
,这是真的,它将打印该短语,然后检查guess
是否不等于number
,这仍然是真的,因为它没有改变,永远。
将需要重复的所有内容放入循环中:
number = 10
guess = int(input("Type in an integer: "))
while guess != number:
if guess < number:
print ("The number is higher")
else:
print ("The number is lower")
guess = int(input("Type in an integer: "))
print ("Good Job!")
print ("Done")
答案 2 :(得分:0)
尝试以下方法:
number = 10
guess = 9
while guess!= number:
guess = int(input("Type in an integer: "))
if guess == number:
print ("Good Job!")
elif guess < number:
print ("The number is higher")
elif guess > number:
print ("The number is lower")
else:
print ("Try Again")
print ("Done")