python - 当用户输入不正确时如何从某个特定点重复代码
问题描述
我是 Python 新手,所以我不太确定基础知识,所以我知道这可能是一个愚蠢的问题。
我正在编写用户输入数字的代码,如果他们弄错了,我希望代码重新启动并要求他们再次猜测,直到正确为止。我该怎么做呢?
print("Let's play a game! Type in a number and see if you guess mine correctly!")
num = input("Type in a number: ")
for x in range (0,1):
if num == "7":
print("Correct!")
else:
print("Nope, try again!")
(我也知道很多代码可能是错误的。)
解决方案
你可以把它放在一个while循环中:
verified = None
while verified is None:
num = input("Type in a number: ")
if num == "7":
print("Correct!")
# if answer is good
verified = True
else:
print("Nope, try again!")