Python Fundamentals · Control Flow

if, elif and else

Choose between several branches. Python checks each condition in order and runs only the first one that is true.

if_elif.py

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)

Step by step

  1. Four test scores to grade.
  2. score is created with the value 92.
  3. 92 >= 90 is True…
  4. …so grade is "A", and Python skips every elif and the else.
  5. It prints 92 A.
  6. score changes from 92 to 74.
  7. Python checks score >= 90 to decide which way the code goes.
  8. 74: not >= 90, so check the elif: 74 >= 70 is True.
  9. grade changes from 'A' to 'B'.
  10. It prints 74 B.
  11. score changes from 74 to 58.
  12. Python checks score >= 90 to decide which way the code goes.
  13. Python checks score >= 70 to decide which way the code goes.
  14. 58: fails the first two checks, passes >= 50.
  15. grade changes from 'B' to 'C'.
  16. It prints 58 C.
  17. score changes from 58 to 35.
  18. Python checks score >= 90 to decide which way the code goes.
  19. Python checks score >= 70 to decide which way the code goes.
  20. Python checks score >= 50 to decide which way the code goes.
  21. 35 fails every condition, so the else branch runs.
  22. It prints 35 fail.
  23. Each score went down the chain until one condition was true. Order matters: if score >= 50 came first, 92 would get a C.