python - 如何使用 try 函数处理 python 中的特定整数异常。如何处理多个除了尝试功能
问题描述
此代码应准确说明用户正在犯什么错误并提示重试。
如何为每个错误制作自定义错误消息?
会不会有更简单的解决方案,比如 c 编程中的 do-while?
while True:
height = int(input("Height: "))
try:
check_answer = int(height)
assert (int(height) > 0)
assert (int(height) < 9)
break
except ValueError:
print("must enter a number")
except (???):
print("enter a number greater than 0")
except (???):
print("enter a number smaller than 9")
解决方案
如果必须使用该assert
语句,则可以将消息作为第二个参数传递,使其成为AssertionError
异常消息:
while True:
try:
height = int(input("Height: "))
assert height > 0, "enter a number greater than 0"
assert height < 9, "enter a number smaller than 9"
break
except ValueError:
print("must enter a number")
except AssertionError as e:
print(str(e))
但是你想要实现的通常是用简单的if
语句来代替:
while True:
try:
height = int(input("Height: "))
except ValueError:
print("must enter a number")
if height <= 0:
print("enter a number greater than 0")
elif height >= 9:
print("enter a number smaller than 9")
else:
break
推荐阅读
- java - 在 JDBC 中运行 IBM Db2 DDL 语句
- r - R中的两个样本T检验
- python - 对行进行分组、排序和透视的有效方法?
- r - 如何仅在 R aod 中使用截距运行 logit/probit 模型?
- python - 总结随机但未定义的数字
- jupyter-notebook - Jupyter nbconvert 无法转换这行 LaTex
- reactjs - 将@fluentui/react 与 webpack 捆绑时出现导出错误
- excel - 在 Excel 电子表格的每张纸上运行一个函数
- python - 使用百分比在单个购买订单中组合不同的 ORDER_TYPE
- c# - 当我的表不可枚举时,如何显示来自 SQL 数据库的列表?我可以很好地使用详细信息视图,但不能使用索引视图