🌱BeginnerControl Flow
Conditionals (if / elif / else)
Making decisions in your program with if, elif, and else statements.
Overview
Conditionals allow a program to take different paths depending on whether conditions are true or false. Python's conditional syntax uses three keywords: if, elif (else-if), and else.
A condition is any expression that evaluates to a truthy or falsy value. Python does not require the condition to be a strict True/False boolean an empty string, 0, None, or an empty list are all falsy; non-empty strings, non-zero numbers, and populated collections are all truthy.
Python does not have a switch/case statement in versions before 3.10, but the match statement (introduced in 3.10) fills that role for structural pattern matching. For older versions, chains of if/elif are the standard approach.
The ternary (one-line conditional) expression `value_if_true if condition else value_if_false` is compact and Pythonic when the logic is simple.
Key Points
- •if block runs when the condition is truthy; elif adds alternative conditions; else is the fallback
- •Indentation defines the block every line in the if block must be indented equally
- •Conditions can be any truthy/falsy expression, not just explicit True/False
- •Ternary: `x = "yes" if condition else "no"` one-liner for simple branching
- •Comparison operators: ==, !=, <, >, <=, >= all return True or False
- •Combine conditions with and, or, not e.g. `if age >= 18 and has_id:`
Examples
Basic if / elif / else
score = 75
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"Score {score} → Grade {grade}") # Score 75 → Grade CTruthy/falsy values in conditions
name = ""
if name:
print(f"Hello, {name}!")
else:
print("No name provided.") # runs because "" is falsy
items = [1, 2, 3]
if items:
print(f"You have {len(items)} items.") # runs list is non-emptyTernary expression
age = 20
status = "adult" if age >= 18 else "minor"
print(status) # adult
# Can also be used inline
print("even" if 42 % 2 == 0 else "odd") # evenCommon Mistakes
- Missing colon after the condition: `if x > 5` needs a colon → `if x > 5:`
- Using = instead of == in a condition: `if x = 5:` is a SyntaxError
- Forgetting that elif and else must align with their if inconsistent indentation causes errors
Note
When you have many elif chains checking the same variable against different values, consider if a dictionary lookup might be cleaner: `grades = {90: "A", 80: "B"}` though if/elif is perfectly fine for most cases.
Exercises
Write Python code to solve each exercise. Run it in your browser and check your output.
Loading editor…
Completed: 0 / 5 exercises
Knowledge Check
Question 1 of 4