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().
这篇关于使用整数作为输入的错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用整数作为输入的错误处理
基础教程推荐
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
