【问题标题】:Checking for an exception and other values in an if statement检查 if 语句中的异常和其他值
【发布时间】:2021-11-20 01:49:09
【问题描述】:

假设我想检查 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?

【问题讨论】:

  • 欢迎来到 Stack Overflow。如果您尝试了该代码并且它有效,那么这就是我们可以为您做的所有事情。这不是讨论论坛、辅导服务或代码质量研讨会。

标签: python if-statement exception


【解决方案1】:

在 Python 中,检查异常的方法是使用 try:except: 块,而不是使用“if”语句。

所以这个问题的答案:

“有没有办法用 'if' 语句检查异常?”是“不”。

你的问题有点不同。您问是否可以 (1) 检查异常并 (2) “在同一个 'if' 语句中”评估另一个表达式。因为你甚至不能做'if'语句中的第一件事,你显然不能同时做。

【讨论】:

    【解决方案2】:

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

    score2 = float(input('Enter the your 2nd score: '))
    
    assert score1 >= 0 and score2 >= 0
    
    except:
    ...
    

    去掉 if 语句。

    【讨论】:

      猜你喜欢
      • 2022-01-01
      • 2021-09-28
      • 2017-04-21
      • 2016-08-27
      • 2016-01-29
      • 1970-01-01
      • 2014-01-18
      • 1970-01-01
      • 2011-11-16
      相关资源
      最近更新 更多