Home > OS >  Checking for an exception and other values in an if statement
Checking for an exception and other values in an if statement

Time:09-28

Let's say I want to check the avarage of 2 test scores. I don't want the user to input any letters or a value less than 0.

What comes to my mind is this code:

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 

Is there a way to check for an exception and if a score is less than 0 in the same if statement?

CodePudding user response:

This is not very efficient; but you can do this after loading score2 in the try:

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

assert score1 >= 0 and score2 >= 0

except:
...

and get rid of the if statement.

CodePudding user response:

In Python, the way to check for an exception is by using a try:except: block, not by using an 'if' statement.

So the answer to this question:

"Is there a way of checking for an exception with an 'if' statement?" is "no."

Your question was a little different. You asked whether you could (1) check for an exception and (2) evaluate another expression "in the same 'if' statement." Since you can't even do the first thing in an 'if' statement, you clearly can't do both.

  • Related