繁体   English   中英

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

[英]How to catch two different types of bad input

我在python 3中编写代码,我需要输出两个不同的字符串,具体取决于输入的内容。 它们都是ValueErrors。

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

我已经尝试过这个问题的方法,但我只得到一条打印的消息。 如何使用try和python捕获空用户输入?

我还试图通过使用while循环忽略来自两个选项之一的ValueError,并尝试使用try除了块来捕获另一个选择:

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

既然你赶上ValueError ,第一个except会一直抓住它。 实际上,如果你看一下ValueError int()引发,它在两种情况下都是一样的:

>>> 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!")

拆分两个错误条件,以便分别处理每个错误条件:

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块将捕获任何非整数值。

由于值错误由其他人解释,您也可以通过此方法执行相同操作

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方法将检查输入是否为int,如果int为else,则isinstance将返回True。 如果a在0-9之间,则返回范围内的答案,否则返回false。

你可以用这种方式改变python输入函数:

请定义一个新的功能

def Input(Message):

设置一个初始值,如

Value = None

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

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

控制I / O错误等

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

最后,您可以返回您的值,它可以是None或true值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM