【问题标题】:How can I add exception for when user inputs a negative number如何在用户输入负数时添加异常
【发布时间】:2020-06-01 13:57:10
【问题描述】:

我正在尝试添加一个例外来识别某人何时输入负数,并回复说您只能输入正数

print('How many cats do you have?')
numCats = input()
try: 
    if int(numCats) >=4:
        print('Thats a lot of cats.')
    else:
        print('Thats not that many cats.')
except ValueError: 
    print('You did not enter a number.')

目前它会响应用户输入字符串而不是整数,但我希望它能够通过打印“您不能使用负数”来响应用户输入 -4 之类的内容。

对 Python 完全陌生,因此非常感谢任何有关如何添加它的建议,谢谢。

【问题讨论】:

标签: python exception except


【解决方案1】:

只是

raise ValueError("you must give a positive number")

【讨论】:

    【解决方案2】:
    print('How many cats do you have?')
    try: 
        numCats = int(input()) #Moving the int() around input() means we aren't calling int() for every if branch.
        #Also, need to move that in here, so it gets caught by the try/except
        if numCats >= 4:
            print('Thats a lot of cats.')
        elif numCats < 0:
            print('You need a positive amount of cats.') #just printing instead of using a raise statement, an exception is unnecessary
        else:
            print('Thats not that many cats.')
    except ValueError: 
        print('You did not enter a number.')
    

    【讨论】:

      【解决方案3】:

      定义你自己的异常类,你可以选择捕获或不捕获:

      class NegativeNumberException(Exception):
          pass
      
      print('How many cats do you have?')
      try:
          numCats = int(input())
          if numCats >=4:
              print('Thats a lot of cats.')
          elif numCats < 0:
              raise NegativeNumberException()
          else:
              print('Thats not that many cats.')
      except ValueError:
          print('You did not enter a number.')
      except NegativeNumberException as e:
          print("You entered a negative number.")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-26
        • 2012-09-15
        • 1970-01-01
        • 2019-09-12
        • 1970-01-01
        • 2021-06-13
        相关资源
        最近更新 更多