Code doesn't work in reverse?

So I was testing to see if it can be done this way. I thought the logic of the following is sound but it won’t return anything but “B”. The “solution” had grade set to F.
I wanted to if I could do it in reverse. Where did I screw up:

def grade_converter(gpa):
grade = “A”

if gpa < 4.0:
grade = “B”
elif gpa < 3.0:
grade = “C”
elif gpa < 2.0:
grade = “D”
elif gpa < 1.0:
grade = “F”

return grade


As always, follow the code:
You have set ‘grade’ to be 2.7.
The first “if” returns True, since, indeed, 2.7 < 4.0 is True

Now, it is the essence of an “if - elif” sequence that once one of them returns True, all of the rest are skipped. That is how ‘elif’ works.

So, once you have True in the first ‘if’, the ‘if’ block is executed, the variable grade is set to “B”, and control skips every ‘elif’ (and the ‘else’, should one be there), and drops straight to the return statement.

Now, consider: Let’s follow the code, again, but suppose that you had order of the grades reversed, the first line being

if gpa < 1.0:
    grade = 'F'

… ?

This makes so much sense.
Thank you for a great response and now I see why it cannot be written the way I wanted. The check from top down needs to be staggered so as not to stop the rest.

So if we did what you propose, the 2.7 that I entered would not return your if gpa<1 true and would go to the next until it is triggered true (please correct me if I have it wrong):

gpa < 1 would return False
gpa < 2 would return False
gpa < 3 would return True and therefore return “C”.

Yes, precisely! :slightly_smiling_face: