Error handling using integers as input(使用整数作为输入的错误处理)
问题描述
我已经设置了这个程序来检查满分 100 分的测试.如果用户输入小于 60,则应该说失败,如果超过 59,则通过.
Ive set up this program that checks the mark out of 100 for a test. If the user inputs less than 60 it should say fail if more than 59, pass.
mark = int(input("Please enter the exam mark out of 100 "))
if mark < 60:
print("
Fail")
elif mark < 101:
print("
Pass")
else:
print("
The mark is out of range")
如果用户不输入整数,我如何让程序不出错.
how do i get the program not to have errors if the user does not input the Integer.
请帮忙,有 14 岁的孩子能理解的快速解决方案吗?
Please help, is there a quick solution that 14 year olds would understand?
推荐答案
将输入保存在变量中,并分别转换为整数:
Save the input in a variable and convert to an integer separately:
import sys
i = input("Please enter the exam mark out of 100 ")
try:
mark = int(i)
except ValueError:
print('
You did not enter a valid integer')
sys.exit(0)
if mark < 60:
print("
Fail")
elif mark < 101:
print("
Pass")
else:
print("
The mark is out of range")
如果失败(即,您收到 ValueError),则打印一条消息并退出.你可以解释(对一个 14 岁的孩子)int() 需要一个有效的整数作为输入,否则它会引发一个 ValueError.这是有道理的,因为 int() 只能转换包含整数的字符串.
If it fails (i.e., you get a ValueError) then print a message and exit. You can explain (to a 14-year old) that int() needs a valid integer as input and it will raise a ValueError otherwise. That makes sense because only strings that contain an integer can be converted by int().
这篇关于使用整数作为输入的错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用整数作为输入的错误处理
基础教程推荐
- 求两个直方图的卷积 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 包装空间模型 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
