python - 检查输入是否为正整数

标签 python

这个问题在这里已经有了答案:





Asking the user for input until they give a valid response

(22 个回答)


6年前关闭。




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

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

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

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

有任何想法吗?

最佳答案

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)

关于python - 检查输入是否为正整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26198131/

相关文章:

Python Twitter 情绪分析错误

python - 为什么 gevent.spawn 在调用 Greenlet.join 之前不执行参数化函数?

python - 在 AND 和 OR 处拆分字符串,保留分隔符

python - 在 lambdify 的 sympy 表达式上使用 numba.autojit

python - 将所有内容放在应用程序中心会弄乱 `DatePickerSingle` 和 `RadioItems`

python - Numpy 突然使用所有 CPU

python - 使用默认系统串行配置的 Pyserial

python - 调试 Apache/Django/WSGI 错误请求 (400) 错误

python - 根据索引列表中的索引获取项目列表

python - 将包含列名称为 "name"的 pandas DataFrame 转储到 mysql 表