所以我目前正在学习如何使用 Python,并且一直在尝试解决我的一个问题,我有一个 if 语句,当输入不正确的值时,我希望它重新启动并再次提出问题。
我相信为此需要一个 while 循环或 for 循环,但是在寻找了一段时间之后我只是不确定我将如何使用这段代码实现它,因此如果有人知道我很想看看如何实现。
x = int(input("Pick between 1,2,3,4,5: "))
if x == 1:
print("You picked 1")
elif x == 2:
print("You picked 2")
elif x == 3:
print("You picked 3")
elif x == 4:
print("You picked 4")
elif x == 5:
print("You picked 5")
else:
print("This is not a valid input, please try again")
#Want to go back to asking the start question again
谢谢,
利亚姆
最佳答案
while
循环是您需要在您的案例中使用的:
x = int(input("Pick between 1,2,3,4,5: "))
while x not in [1, 2, 3, 4, 5]:
print("This is not a valid input, please try again")
x = int(input("Pick between 1,2,3,4,5: "))
print("You picked {}".format(x))
我们检查 x
是否不在数字列表 [1, 2, 3, 4, 5]
中,然后我们要求用户再次输入一个数字.
如果条件不是True
(意味着 x 现在在列表中),那么我们会向用户显示输入的数字。
关于Python - 如果输入的值不正确,则重新启动 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40953565/