使用整数作为输入的错误处理

2022-01-14 00:00:00 python integer

问题描述

我已经设置了这个程序来检查满分 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().

相关文章