ERJAN
ERJAN

Reputation: 24500

How can I refactor this if elif statements?

There is list of grades - [a,b,c,d,e,f]

grade = int(input())
if grade >= 90 and grade <= 100:
    print('a')
elif grade >=70 and grade <= 80:
    print('b')
elif grade >=60 and grade <= 70:
    print('c')
elif grade >= 50 and grade <= 60:
    print('d')
elif grade < 50:
    print('e')

How can I rewrite this elegantly in 2-3 lines of code?

Like, there is dictionary with key grades 'a', 'b', 'c', 'd' and it prints depending on the grade?

Upvotes: 0

Views: 138

Answers (3)

ncica
ncica

Reputation: 7206

grades =  {'a': range(90,100), 'b': range(80,90),'c': range(70,80), 'd': range(60,70), 'e': range(50,60)}

grade = int(input())

for key,value in grades.items():
    if grade in value:
        print (key)

or just use list comprehension:

grades =  {'a': range(90,100), 'b': range(80,90),'c': range(70,80), 'd':range(60,70), 'e': range(50,60)}

grade = int(input())

print ([key for key,value in grades.items() if grade in value][0])

Upvotes: 4

Don
Don

Reputation: 17606

You could zip grades and thresholds:

grades = "edcba"
limits = [50, 60, 70, 80, 100]  # I think that 80-90 gap is not intentional
grade = int(input())
for limit, letter in zip(limits, grades):
    if grade <= limit:
        print(letter)
        break
else:
    print("Not found!")

Upvotes: 2

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520878

Well you could easily get rid of one half of the range checks, by rephrasing as follows:

grade = int(input())
if grade < 50:
    print('e')
elif grade <= 60:
    print('d')
elif grade <= 70:
    print('c')
elif grade <= 80:
    print('b')
elif grade >= 90 and grade <= 100:
    print('a')
else
    print('unknown')

I am not sure if your 90 <= grade <= 100 range is accurate, or if you intended for it to be adjacent to the previous lower range. In any case, it does not change my suggested refactor much.

Upvotes: 1

Related Questions