首页 > 解决方案 > 用户输入错误格式时如何通知错误?

问题描述

当用户按要求插入不是整数的输入时如何通知错误?

例如:

number = int(input("Input the number: "))

我想编写如下代码:如果数字“不是”整数,那么

if number is not integers 
            print("The input was not numerical value. Please try again")
        else:
            print ("Input "+ str(number) + " elements in the list:")

你能帮助我吗。

谢谢!

标签: pythonif-statementinteger

解决方案


try/except 语句应该很合适:

try:
    number = int(input("Input the number: "))
    print ("Input "+ str(number) + " elements in the list:")
except ValueError:
    print("The input was not numerical value. Please try again")

推荐阅读