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
- Kivy 使用 opencv.调整图像大小 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
