首页 > 解决方案 > 检查 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?

标签: pythonif-statementexception

解决方案


这不是很有效;但是您可以在加载后执行此score2操作try

score2 = float(input('Enter the your 2nd score: '))

assert score1 >= 0 and score2 >= 0

except:
...

并摆脱 if 语句。


推荐阅读