python中的输入异常 [英] exception in input in python

查看:187
本文介绍了python中的输入异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

运行以下代码时:

try:
   key=int(input())
except ValueError as string:
   print("Error is within:",string)

例如,如果将'rrr'放进去,则会出现此异常,因为'rrr'不支持(int)

for example, if one puts 'rrr' this exception will rise, since 'rrr' does not support (int)

: int()的无效文字,基数为10:'rrr'

However, instead ot putting the actual string, it puts: "invalid literal for int() with base 10: 'rrr' "

我如何使其工作,以便变量'string'实际得到错误的输入,用户给出的(在此示例中,我希望它打印:错误在rrr内)

How do I make it work so that the variable 'string' actually gets the wrong input that the user gave (in this example, I want it to print: 'Error is within: rrr')

非常感谢

推荐答案

您的问题来自以下事实:变量 string 是ValueError异常的错误消息。如果您想打印出用户的无效输入,则需要创建一个变量来存储用户的输入,然后再尝试/例外。例如:

Your issue comes from the fact that the variable string is the error message for a ValueError exception. If you wanted to print out the user's invalid input, you would need to create a variable that stores the user's input before your try/except. For example:

userInput = input()
try:
   key=int(userInput)
except ValueError:
   print("Error is within:",userInput)

这篇关于python中的输入异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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