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

时间:2023-04-14
本文介绍了使用整数作为输入的错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

这篇关于使用整数作为输入的错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:Long Int 文字 - 无效的语法? 下一篇:Int 转换不起作用

相关文章