【问题标题】:How to inform error when user leaving wrong format input?用户输入错误格式时如何通知错误?
【发布时间】:2021-01-13 21:32:14
【问题描述】:

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

例如:

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

你能帮帮我吗?

谢谢!

【问题讨论】:

  • 你能举一个int可以产生的非整数的例子吗?
  • 关于这个的帖子已经很少了,例如:stackoverflow.com/questions/1265665/…
  • @ScottHunter 你不懂我的意思。例如:有人输入的字符不是整数,所以系统会打印“输入的不是数值。请重试”。
  • 你没有得到 my 的意思是:number 已经被分配了调用int 的结果,然后你才能进行任何测试。

标签: python if-statement integer


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-31
    • 2021-11-04
    • 1970-01-01
    • 2021-08-23
    相关资源
    最近更新 更多