python - 如何在用户输入负数时添加异常
问题描述
我正在尝试添加一个例外以识别何时有人输入负数,并回复说您只能输入正数
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 来说是全新的,所以任何关于如何添加它的建议都将非常感激,谢谢。
解决方案
定义您自己的异常类,您可以选择是否捕获它:
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.")
推荐阅读
- unit-testing - 将 (Zusand) 函数模拟与 Jest 一起使用会导致“TypeError:create is not a function”
- qr-code - 我需要为其他用户创建一个输入文本字段来放置他们的链接?我如何使用 api 做到这一点?
- python - 用傅里叶变换python去除噪声
- firebase - Flutter中TextFormField中hintText的值是否可以保存?
- json - SharePoint Online - 查找在表单中显示多个值
- stored-procedures - 如何使用 ef 核心和干净的架构调用存储过程
- javascript - 使用概率 javaScript 获取结果
- python - 由于问题而不随机化文件名
- javascript - 当我清除文本区域时显示弹出窗口。只想显示数字
- c# - 如何序列化和反序列化一个巨大的 Trie?