Python - If...Else

Overview

Estimated time: 20–30 minutes

Write clear conditional logic with if, elif, and else, including common idioms.

Learning Objectives

  • Write simple and nested conditionals.
  • Use truthiness and explicit comparisons appropriately.
  • Know when to refactor to dictionaries or pattern matching (3.10+).

Prerequisites

Basic examples

score = 87
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
else:
    grade = "C"
print(grade)

Conditional expressions

age = 20
category = "adult" if age >= 18 else "minor"
print(category)

Common Pitfalls

  • Deeply nested ifs: consider early returns or mapping tables.
  • Relying on truthiness when 0 and "" are valid but falsy inputs—be explicit.

Checks for Understanding

  1. What keyword is used for additional branches after if?
  2. How do you write a one-line conditional assignment?
Show answers
  1. elif
  2. x = A if cond else B

Exercises

  1. Map numeric scores to letters with if/elif/else.
  2. Refactor a long if/elif on strings into a dictionary lookup.