jeudi 16 janvier 2020

Does someone know how to simplify endless if elif else statements in this algorithm?

I am trying to write a grade converter that changes number grades like 88% to a letter grade (i.e. B+) but I feel that there is a simpler way than using endless elif statements. Ideally I would like to have one condition that determines the letter based on the range and another condition that determines whether to assign a + or - based on a separate range. Here is the current code:

def convert_score_to_grade_w_plus_and_minus(score):
if score in range(98, 101):
    return 'A+'
elif score in range(93, 98):
     return 'A'
elif score in range(90, 93):
    return 'A-'
elif score in range(88, 90):
    return 'B+'
elif score in range(83, 88):
    return 'B'
elif score in range(80, 83):
    return 'B-'
elif score in range(78, 80):
    return 'C+'
elif score in range(73, 78):
    return 'C'
elif score in range(70, 73):
    return 'C-'
elif score in range(68, 70):
    return 'D+'
elif score in range(63, 68):
    return 'D'
elif score in range(60, 63):
    return 'D-'
elif score in range(60):
    return 'F'
else: 
    return 'INVALID SCORE'

Aucun commentaire:

Enregistrer un commentaire