2016-12-03 27 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

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