Lia*_*ton 3 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
Run Code Online (Sandbox Code Playgroud)
谢谢,
利亚姆
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))
Run Code Online (Sandbox Code Playgroud)
我们检查是否x不在数字列表中[1, 2, 3, 4, 5],然后我们要求用户再次输入一个数字.
如果条件不是True(表示x现在在列表中),那么我们向用户显示输入的数字.