【问题标题】:How to catch two different types of bad input如何捕捉两种不同类型的错误输入
【发布时间】:2014-11-01 18:18:05
【问题描述】:

我正在 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

我已经尝试过这个问题的方法,但我只收到一条打印的消息。 How to catch empty user input using a try and except in python?

我还尝试通过使用 while 循环并尝试使用 try except 块捕获另一个选项来忽略两个选项之一中的 ValueError:

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

【问题讨论】:

  • if chooseword = "": 是语法错误(单个=,在if 语句中是非法的)。

标签: python exception


【解决方案1】:

由于您正在捕获 ValueError,第一个 except 将始终捕获它。事实上,如果你看一下 ValueError int() raises,这两种情况都是一样的:

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

【讨论】:

  • 谢谢!我一直在寻找可行的方法,我尝试了这个,但我错过了 int(word) 在与输入不同的步骤中!
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    因为值错误别人解释过,你也可以用这个方法来做

    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 为 False,isinstance 将返回 True。如果 a 在 0-9 之间,则返回范围内的答案,否则返回 false。

    【讨论】:

      【解决方案4】:

      你可以这样改造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 或真值。

      【讨论】:

        猜你喜欢
        • 2023-01-24
        • 2012-07-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-14
        • 1970-01-01
        • 2010-12-06
        • 2021-12-06
        相关资源
        最近更新 更多