elif (else if) adds another condition to an if. Python checks the conditions from the top and runs the first block whose condition is true, skipping the rest, so the order matters: put the most specific or the highest threshold first. A final else catches everything that did not match.
A chain of if, elif, else is one statement. Compare that with several separate if statements, which are all checked and can all run.
def size(n):
if n >= 1000:
return "large"
elif n >= 100:
return "medium"
else:
return "small"Your task
Write grade(score) that returns "A" for 90 and above, "B" for 80 and above, "C" for 70 and above, "D" for 60 and above, and "F" for anything lower.
Hint 1
Start with the highest threshold: if score >= 90.
Hint 2
Each elif only runs when every condition above it was false, so elif score >= 80 already means the score is below 90.
Show the solution
def grade(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"