lundi 27 septembre 2021

Checking for an exception and other values in an if statement

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?

Aucun commentaire:

Enregistrer un commentaire