基本上,我的代码不会“结束”。我肯定知道我的代码编写方式有问题,但是我不知道该在哪里修复或更改。我尝试了很多不同的事情。
所以这是我第一次尝试编写Guessing Game Challenge。 我觉得我不太了解如何利用while循环,因为无论我尝试给出正确答案的次数是多少,我的游戏都不会停止。谁能告诉我我哪里出问题了?非常感谢。
#import random was used
answer = random.randint(1,101) #This is the answer for the specific game.
print(answer) #NEED TO DELETE THIS LINE AFTER Successful answer
print()
print()
print ("Enter a number!")
guess = int(input()) #Player guesses here.
while True:
if guess == answer:
print("YOU GOT THE ANSWER! WELL DONE")
break
elif guess <1 or guess > 100:
print("OUT OF BOUNDS")
break
elif abs(guess - answer) <= 10 or abs(answer - guess) <= 10:
print(input("WARM. YOU ARE GETTING CLOSER."))
elif abs(guess - answer) > 10 or abs(answer - guess) > 10:
print(input("COLD. TRY AGAIN."))
else:
print("ERROR")
预期:我希望当我的猜测整数==以不同的尝试回答时,它将返回到“您已获得答案!做得好!”。 实际的:即使我写了实际的答案,代码也会无限循环。
答案 0 :(得分:1)
当您输入以下内容时:
elif abs(guess - answer) <= 10 or abs(answer - guess) <= 10:
print(input("WARM. YOU ARE GETTING CLOSER."))
elif abs(guess - answer) > 10 or abs(answer - guess) > 10:
print(input("COLD. TRY AGAIN."))
您没有将输入分配给变量 guess ,因此它始终是您在开始时输入的值,因此,给出的第一个答案将在循环中重复。
将该片段更改为:
elif abs(guess - answer) <= 10 or abs(answer - guess) <= 10:
guess = int(input("WARM. YOU ARE GETTING CLOSER."))
elif abs(guess - answer) > 10 or abs(answer - guess) > 10:
guess = int(input("COLD. TRY AGAIN."))
重新分配 guess 变量,它将起作用。
答案 1 :(得分:0)
这是一种非常简单的方法(不是最有效的方法):
cycle = True
while cycle:
if guess == answer:
print("YOU GOT THE ANSWER! WELL DONE")
cycle = False
elif guess <1 or guess > 100:
print("OUT OF BOUNDS")
cycle = False
elif abs(guess - answer) <= 10 or abs(answer - guess) <= 10:
print(input("WARM. YOU ARE GETTING CLOSER."))
elif abs(guess - answer) > 10 or abs(answer - guess) > 10:
print(input("COLD. TRY AGAIN."))
else:
print("ERROR")`
希望这对您有帮助,学习愉快!