2016-12-03 109 views
3

所以我目前正在学习如何使用Python,并试图解决我的问题,我有一个if语句,当输入了错误的值时,我想它重新启动并再次提出问题。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 

感谢,

利亚姆

+1

你需要使用一个while循环 –

回答

-1
while True: 
    try: 
     x = int(input("Pick between 1,2,3,4,5: ")) 

    except ValueError: 
     print("oops"): 

    else : 

     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") 

喜欢这个?

+1

如果我输入'6'到这个,我不会得到'ValueError'。 –

3

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

+1

你也可以在'while x not in range(1,6)'。 –

+1

当然,因为OP已经提到了这个序列,所以只需要更加明确。 – ettanany

+1

的确如此。你的回答非常好! –