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.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With