2015-10-13 156 views
-5

所以我要問客戶端重新輸入變量如果不是整數,或者是小於或等於0,我不能讓它得到一個程序錯誤,並結束它。Python的驗證,如果輸入是int和大於0

def enter_amount(): 


amount=input("Enter amount:") 
while (not isinstance(amount, int)) or amount<=0: 
    amount=input("The amount can't be negative, please try again:") 
return amount 

試過這個,它總是失敗了。如果您有任何想法,我將不勝感激。

+0

這是蟒蛇2.x或3.x的?在2.x中,_input_評估用戶輸入一個Python表達式,通常是一個不錯的選擇,而_raw_input_給你一個字符串。在3.x中,_input_給你一個字符串,而不是一個int。 – tdelaney

+2

「沒有工作。」太好了,真棒,***如何。*** –

+0

這是蟒蛇3.x的Ook,那我該如何檢查這一點,如果不符合,重試?如果輸入的字符串不管用戶寫什麼,那麼在這種情況下這個例子幾乎是沒用的。 –

回答

1

您需要輸入轉換爲整數,然後檢查該值。由於用戶可能會輸入垃圾,因此您必須通過捕獲值異常來處理整數轉換。

def get_amount(): 
    while True: 
     amount = input("Enter amount: ") 
     try: 
      val = int(amount) 
      if val >= 0: 
       break 
      else: 
       print("Amount can't be negative, try again") 
     except ValueError: 
      print("Amount must be a number, try again") 
    return val 
-1

不能使用回的功能之外!把你的代碼包裝在一個函數中,它應該沒問題。

def test(): 
    amount=input("Enter amount:") 
    while (not isinstance(amount, int)) or amount<=0: 
     amount=input("The amount can't be negative, please try again:") 
    print(amount) 
    return amount 

test() 
+0

這是一個功能,忘記把它放在那裏,對不起。 –

0
def getUserAmount(): 
    while True: 
     amount = input("Enter amount: ") 
     try: 
      value = int(amount) 
      if value >= 0: 
       break 
      else: 
       print("Amount is negative, try again") 
     except ValueError: 
      print("Amount must be a number, try again") 

    return value 

main()