Choose between several branches. Python checks each condition in order and runs only the first one that is true.
Python · beginner · 7 min · 23 steps · free
marks = [92, 74, 58, 35]
for score in marks:
if score >= 90:
grade = "A"
elif score >= 70:
grade = "B"
elif score >= 50:
grade = "C"
else:
grade = "fail"
print(score, grade)score is created with the value 92.92 A.score changes from 92 to 74.score >= 90 to decide which way the code goes.grade changes from 'A' to 'B'.74 B.score changes from 74 to 58.score >= 90 to decide which way the code goes.score >= 70 to decide which way the code goes.grade changes from 'B' to 'C'.58 C.score changes from 58 to 35.score >= 90 to decide which way the code goes.score >= 70 to decide which way the code goes.score >= 50 to decide which way the code goes.35 fail.score >= 50 came first, 92 would get a C.if x > 1: a elif x > 3: b. Which runs?Answer: a. x > 1 is true first, so the elif is skipped.
Answer: When no condition above it was true. else is the fallback.
← Booleans, Comparisons and Logic · while Loops →