Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a shorter way for if-else chains?

if (80 <= m <= 100):
    g = "A"
elif (70 <= m < 80):
    g = "B"
elif (60 <= m < 70):
    g = "C"
elif (50 <= m < 60):
    g = "D"
elif (m < 50):
    g = "U"

This is basically a grade measuring piece of code that takes in value m, meaning mark, and obtains grade g. Is there a shorter not necessarily more pythonic way for the same purpose?

Thanks in advance.

like image 794
Terrornado Avatar asked Dec 01 '22 11:12

Terrornado


1 Answers

Firstly, you can simplify by removing one of the bounds:

if m >= 80:
    g = "A"
elif m >= 70:
    g = "B"
elif m >= 60:
    g = "C"
elif m >= 50:
    g = "D"
else:  # default catch-all
    g = "U"

Secondly, you could capture the repetitive nature of the process by a loop (with the default case presenting an option for a for-else construct):

# iterator: ('A', 80) -> ('B', 70) -> ...
for grade, score in zip('ABCD', (80, 70, 60, 50)):
    if m >= score:
        g = grade
        break
else:  # executed if for-loop isn't 'break'-ed out of
    g = 'U'
like image 97
user2390182 Avatar answered Dec 04 '22 08:12

user2390182