2014-10-04 166 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循环,所以码继续重复操作,直至有效的答案,并给出了里面的右输入测试。