Every (if) statement is checking the expression for True or False.
If the expression is True - the block of code after the colon ( is executed.
If the expression is False - the machine evaluates the next if statement and so forth till the (return)
Let’s assume my GPA is 2.1 and that’s why I am writing this…
Here I defined a function:
def grade_converter(gpa):
if gpa >= 4.0:
return "A"
if gpa >= 3.0:
return"B"
if gpa >= 2.0:
return "C"
if gpa >= 1.0:
return "D"
else:
return "F"
And here I am defining a variable and assigning it a grade by calling a function (grade_converter) with my 2.1 GPA.
grade = grade_converter(2.1)
Here is what the machine is thinking:
grade_converter(2.1):
if 2.1 >= 4.0: False, check next expression
return “A”
if 2.1 >= 3.0: False, check next expression
return"B"
if 2.1 >= 2.0: True, execute the code and end the function
return “C”
if gpa >= 1.0:
return “D”
else:
return “F”
Here the machine prints my grade “C”, same result as if I used (elif) instead of 2,3 and 4th (if) and I have a question:
If I achieved same results with (if) why do we need (elif)?
Help me understand why when using if and then print(), we’d get C,D and F. Doesn’t if function work like this: when if condition is met it doesn’t move to next line. Isn’t this true ? Why is C, D and F getting printed then.
I think I just had the problem you did – I entered a function that the assessment kept coming back as "didn’t return " on repeatedly, then checked the solution after a long frustrating period of checking my code only to find it was only minorly different.
… then proceeded to modify my code back to exactly what it was beforehand, only to find it worked just fine now.
I tried using this code for exercise 11/13 of Control Flow: Else If Statements and it worked.
Not sure, if this is correct.
Why id grade assigned ‘F’ value?
I get the error message “maximum recursion depth exceeded in comparison”. I’ve never seen this error before and I don’t understand why I got this error. Can someone please explain why I get this message and also why my code doesn’t print “C” in the console? Thank you.