【问题标题】:Python - Restarting an if statement if an incorrect value is enteredPython - 如果输入了不正确的值,则重新启动 if 语句
【发布时间】:2016-12-03 23:14:47
【问题描述】:

所以我目前正在学习如何使用 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循环

标签: python loops if-statement


【解决方案1】:

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 现在在列表中),那么我们将输入的数字显示给用户。

【讨论】:

  • 你也可以while x not in range(1, 6).
  • 当然,只是想更明确一点,因为OP已经提到了这个序列。
猜你喜欢
  • 1970-01-01
  • 2016-03-20
  • 2016-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-01
  • 2018-09-21
相关资源
最近更新 更多