python - 检查 if 语句中的异常和其他值
问题描述
假设我想检查 2 个考试成绩的平均值。我不希望用户输入任何字母或小于 0 的值。
我想到的是这段代码:
while True:
try:
score1 = float(input('Enter the your 1st score: '))
score2 = float(input('Enter the your 2nd score: '))
except:
print('Invalid value, try again...')
continue
if (score1 < 0 or score2 < 0):
print('Invalid value, try again...')
continue
print(f'Your average is {(score1 + score2) / 2}')
break
有没有办法检查异常以及同一 if 语句中的分数是否小于 0?
解决方案
这不是很有效;但是您可以在加载后执行此score2
操作try
:
score2 = float(input('Enter the your 2nd score: '))
assert score1 >= 0 and score2 >= 0
except:
...
并摆脱 if 语句。
推荐阅读
- css - How to Put Spacing Between these Options Using CSS?
- c# - VSIX 扩展 - 更改 DLL 的路径
- javascript - 反应酶单元测试错误
- c# - NET Core Cors 引发错误
- c# - 在 Bot Framework 中使用 FormFlow 对话框
- python - 如何在seaborn lineplot上绘制虚线?
- google-analytics - 使用 gtag 发送自定义 utm_source?
- ckeditor - CKEditor:允许段落内的跨度标签
- ruby-on-rails - 当模型名称带有“che”后缀时,控制器的变量会被修改
- php - 使用 $variable 时 mb_detect_encoding 不起作用