2014-10-04 207 views
0

我需要檢查用戶輸入的內容是否爲正值。如果不是,我需要以msgbox的形式打印錯誤。檢查輸入是否爲正整數

number = input("Enter a number: ") 
    ################################### 

    try: 
     val = int(number) 
    except ValueError: 
     print("That's not an int!") 

上面的代碼似乎沒有工作。

任何想法?

+0

它不起作用? – 2014-10-04 23:25:08

+1

檢查整數大於或等於0. – 2014-10-04 23:25:40

+0

您的意思是'如果val> = 0' – 2014-10-04 23:25:56

回答

5
while True: 
    number = input("Enter a number: ") 
    try: 
     val = int(number) 
     if val < 0: # if not a positive int print message and ask for input again 
      print("Sorry, input must be a positive integer, try again") 
      continue 
     break 
    except ValueError: 
     print("That's not an int!")  
# else all is good, val is >= 0 and an integer 
print(val) 
+0

Nope .............仍然是同樣的錯誤。 – shivampaw 2014-10-04 23:36:15

+1

我的代碼沒有錯誤,你說什麼錯誤? – 2014-10-04 23:36:59

+0

我的完整代碼:http://pastebin.com/yctSQLz0 – shivampaw 2014-10-04 23:39:00

0

你所需要的是這樣的:

goodinput = False 
while not goodinput: 
    try: 
     number = int(input('Enter a number: ')) 
     if number > 0: 
      goodinput = True 
      print("that's a good number. Well done!") 
     else: 
      print("that's not a positive number. Try again: ") 
    except ValueError: 
     print("that's not an integer. Try again: ") 

一個while循環,所以碼繼續重複操作,直至有效的答案,並給出了裏面的右輸入測試。