2015-10-04 46 views
0

我希望用戶輸入1,2或3.但是,當我測試它並輸入1,2或3時,即使條件爲False,它仍會運行。我一直在改變和和或的條件,但我似乎無法解決它。任何幫助將不勝感激。即使在條件爲False後循環運行

def get_input(): 
    user_input = input("Enter a number 1,2 or 3: ") 

    while (user_input != 1) and (user_input != 2) and (user_input != 3) : 
     print('Invaild input!') 
     user_input = input("Enter a number 1,2 or 3 : ") 
+0

你的假設是錯誤的。該程序按照它的要求運行。因此表達式不是錯誤的。 – user2864740

+1

您有不同類型的值 - '「1」!= 1#True' –

+0

感謝Jonathan,但是如何處理用戶輸入的字符串或數字不是1 2或3 – user1995933

回答

1

您正在閱讀字符串,您應該將其轉換或使用字符串。因此,條件應該是

(user_input != "1") and (user_input != "2") and (user_input != "3") 
1

因爲從input()返回值是一個字符串(由引號包圍),而不是一個整數。

即。

"1"是不一樣的東西1

要修復它改變這一行。

while (user_input != "1") and (user_input != "2") and (user_input != "3") : 
相關問題