因此,我目前正在学习如何使用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在您的案例中需要使用loop:

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](意味着x现在在列表中),那么我们将向用户显示输入的号码。

10-04 16:24
查看更多