使用整数作为输入进行错误处理 [英] Error handling using integers as input

查看:101
本文介绍了使用整数作为输入进行错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设置了这个程序,检查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("\nFail")
elif mark < 101:
    print("\nPass")
else:
    print("\nThe 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('\nYou did not enter a valid integer')
    sys.exit(0)
if mark < 60:
    print("\nFail")
elif mark < 101:
    print("\nPass")
else:
    print("\nThe 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().

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆