出于某种原因,即使我得到了正确答案,也没有打印出“正确答案”。我不知道为什么。
import random
y = random.randint(1,6)
start_game = input("Pick a number between 1 and 6")
while start_game != y:
if start_game > y:
print("guess too high")
start_game = input("Pick a number between 1 and 6")
elif start_game < y:
print("guess too Low")
start_game = input("Pick a number between 1 and 6")
else:
print("correct guess")`
答案 0 :(得分:1)
在检查if, elif, else
条件之前,您将退出while循环。
您检查的第一件事是while循环的条件,如果y = start_game
退出它。你无法达到其他条件。
在while循环之后移动你的打印件。
此外,您还需要将输入转换为int。
这样:
import random
y = random.randint(1,6)
start_game = int(input("Pick a number between 1 and 6"))
while start_game != y:
if start_game > y:
print("guess too high")
start_game = int(input("Pick a number between 1 and 6"))
elif start_game < y:
print("guess too Low")
start_game = int(input("Pick a number between 1 and 6"))
print("correct guess")
问题是,它将进入循环,首先检查循环的条件,然后它将检查if语句,但是,if,elif,else检查在条件之一为真时立即停止,这意味着,例如即使y < start_game
,你也会要求另一个输入,但是因为你输入了if,所以elif和else条件不会被检查导致循环结束,那么它会回到检查循环条件等。
答案 1 :(得分:1)
正如@xoxel回答的那样,问题是你永远不会进入else
子句,因为当你start_game != y
突破while循环时。
你可以稍微改变它,它可能会更清楚:
while True:
if start_game == y:
print("correct guess")
break
elif start_game > y:
print("guess too high")
start_game = int(input("Pick a number between 1 and 6"))
elif start_game < y:
print("guess too Low")
start_game = int(input("Pick a number between 1 and 6"))
此循环将始终执行,因为其评估为True
。然后它检查它是否得到了正确的猜测,如果确实有则中断 - 否则它会要求用户输入另一个输入。