Python 当用户输入负数时,如何添加异常

Python 当用户输入负数时,如何添加异常,python,exception,except,Python,Exception,Except,我试图添加一个例外,以便在有人输入负数时识别,并用一句话来回答,您只能输入正数 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('

我试图添加一个例外,以便在有人输入负数时识别,并用一句话来回答,您只能输入正数

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来说是全新的,因此,如果您对如何添加此内容有任何建议,我们将不胜感激,谢谢。

这只是

raisevalueerror(“您必须给出一个正数”)

print(“您有多少只猫?”)
尝试:
numCats=int(input())#在input()周围移动int()意味着我们没有为每个if分支调用int()。
#另外,需要将其移到这里,这样它就会被try/except捕获
如果numCats>=4:
打印('那是很多猫')
elif numCats<0:
打印(“您需要正数量的CAT”)#只需打印而不使用raise语句,不需要例外
其他:
打印(“那不是很多猫。”)
除值错误外:
打印('您没有输入数字')

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

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.")
class NegativeEnumberException(异常):
通过
打印('你有多少只猫?')
尝试:
numCats=int(输入())
如果numCats>=4:
打印('那是很多猫')
elif numCats<0:
引发NegativeEnumberException()
其他:
打印(“那不是很多猫。”)
除值错误外:
打印('您没有输入数字')
除NegativeEnumberException为e外:
打印(“您输入了负数。”)

您已经知道如何针对常数正值进行测试。那么负数有什么问题呢?您可能想阅读python教程。。。