Python - 如果输入的值不正确,则重新启动 if 语句

标签 python loops if-statement

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

相关文章:

python - 如何比较 Python 3 中的 numpy 字符串

python - 如何在模板中引用函数的结果? Django

javascript - 访问嵌套对象 (JS) 中的信息

javascript - 有没有办法将对象而不是数组发送到后端? -ReactJS

if-statement - 如何在Jmeter测试计划中实现If Else block ?

php - if 语句不需要执行操作

python - 如何在scrapy中跟随之前修改url?

python - GDB pretty-print : Python Exception <type 'exceptions.LookupError' > no codec search functions registered: can't find encoding

java - ANDROID - 在线程内循环

python - Python检查输入变量是否与格式匹配