如何捕获两种不同类型的错误输入

1 投票
4 回答
2407 浏览
提问于 2025-05-01 01:03

我正在用Python 3写代码,需要根据输入的不同输出两个不同的字符串。它们都是值错误(ValueError)。

try:
    number = False
    while number == False:
        chooseword = int(input("Please enter an integer number (0<=number<10) to choose the word in the list: "))

except ValueError: #empty input
    print("Empty input!")
except ValueError: #non-integer, non-empty input
    print("Input must be an integer!")
else: #do stuff

我尝试了这个问题中的方法,但我只得到一个打印的信息。如何在Python中使用try和except捕获空用户输入?

我还尝试通过使用while循环来忽略其中一个选择的值错误,然后用try except块来捕获另一个选择:

empty = True
while empty == True:
    chooseword = int(input("Please enter an integer number (0<=number<10) to choose the word in   the list: "))
    if chooseword = "":
        empty = True
暂无标签

4 个回答

0

你可以用这种方式来改进Python的输入功能:

请定义一个新的函数,比如:

def Input(Message):

设置一个初始值,比如:

Value = None

在输入的值不是数字之前,尝试获取一个数字。

while Value == None or Value.isdigit() == False:

处理输入输出错误等等。

try:
    Value = str(input(Message)).strip()
except InputError:
    Value = None

最后,你可以返回你的值,这个值可以是None(空值)或者一个真实的值。

0

正如其他人解释的那样,值错误可以通过这种方法来处理。

while True:
    answer = input('Enter a number: ')
    if isinstance(answer,int) and answer in range(0,10):
        do_what_you want()
        break
    else:
        print "wrong Input"
        continue

print answer

instance 方法会检查输入的内容是不是整数,如果是整数,isinstance 就会返回 True,否则返回 False。answer in range 会检查 a 是否在 0 到 9 之间,如果在这个范围内就返回 True,否则返回 False。

1

把这两种错误情况分开处理,这样每种情况都能单独应对:

number = None
while number is None:
    chooseword = input("Please enter an integer number (0<=number<10) to choose the word in the list: ")
    if not chooseword.strip():
        print("Empty input!")
    else:
        try:
            number = int(chooseword)
        except ValueError:
            print("Input must be an integer!")

在这种情况下,chooseword.strip() 会去掉输入中的所有空格字符,这样如果输入是空的或者全是空格,就会被当作长度为零的字符串来处理。如果有输入的话,try/except 这个块会捕捉到任何不是整数的值。

2

因为你在捕捉 ValueError,所以第一个 except 总是会把它抓住。实际上,如果你看看 int() 抛出的 ValueError,在这两种情况下都是一样的:

>>> int('')
ValueError: invalid literal for int() with base 10: ''
>>> int('1.2')
ValueError: invalid literal for int() with base 10: '1.2'

如果你想特别处理空的情况,只需要查看这个异常:

try:
  word = input("Please enter an integer number (0<=number<10) to choose the word in the list: ")
  word = int(word)
except ValueError as e:
  if not word:
    print("Empty!")
  else:
    print("Invalid!")

撰写回答