Python 检查输入是否为正整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26198131/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:12:40  来源:igfitidea点击:

Check if input is positive integer

python

提问by shivampaw

I need to check whether what the user entered is positive. If it is not I need to print an error in the form of a msgbox.

我需要检查用户输入的内容是否是肯定的。如果不是,我需要以 msgbox 的形式打印错误。

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

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

The above code doesn't seem to be working.

上面的代码似乎不起作用。

Any ideas?

有任何想法吗?

回答by Padraic Cunningham

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)

回答by W1ll1amvl

what you need is something like this:

你需要的是这样的:

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: ")

a while loop so code continues repeating until valid answer is given, and tests for the right input inside it.

一个while循环,因此代码继续重复直到给出有效答案,并测试其中的正确输入。