python - 用户输入错误格式时如何通知错误?
问题描述
当用户按要求插入不是整数的输入时如何通知错误?
例如:
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:")
你能帮助我吗。
谢谢!
解决方案
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")
推荐阅读
- html - 图像与其容器之间的微小空间
- javascript - 简单计数器 - 数据集无法正常工作
- javascript - Javascript:为什么字符串的相等对于更长的字符串需要更长的时间?
- mysql - 硬币翻转 - 差距和孤岛问题 MySQL
- c# - ControlTemplate 中的嵌套 ScrollViewer ScrollChanged
- node.js - 使用 NODEJS 保存在 Mongodb 后如何获得响应
- maven - IntelliJ UnitTests Kotlin 和 Java 同名
- sql - 如何在 postgresql 语句中使用时间偏移
- android - Google PAD(快速跟随)可以减小 apk 大小吗?
- python - 将数据框中的单列转换为行 | 熊猫 Facebook 广告