Lesson 4.2: if, elif, and else Statements
What You'll Learn
- How to use
ifstatements to run code conditionally - How to add alternative paths with
else - How to check multiple conditions with
elif - The critical role of indentation in Python
- Common patterns and best practices
The if Statement
The if statement is the most fundamental decision-making tool in Python.
It lets you run a block of code only when a condition is True.
True. If the condition is False, the block is skipped entirely.
# Basic if statement syntax if condition: # This code runs only if condition is True do_something()
Here is a concrete example:
temperature = 35 if temperature > 30: print("It's a hot day!") print("Stay hydrated!") print("Weather check complete.")
Notice three critical things: (1) the condition temperature > 30 comes after
if, (2) there is a colon at the end of the if line,
and (3) the code that runs conditionally is indented.
Indentation Matters!
In Python, indentation is not optional — it is part of the syntax. The indented block
after an if statement defines what code belongs to that condition.
Use 4 spaces for each level of indentation (this is the Python standard).
: at the end of the if line,
or mixing tabs and spaces in indentation, will cause a SyntaxError or IndentationError.
score = 85 if score >= 70: print("You passed!") # Part of the if block print("Congratulations!") # Also part of the if block print("Your score was:", score) # NOT part of the if block - always runs
# What happens when the condition is False? score = 50 if score >= 70: print("You passed!") # Skipped because 50 >= 70 is False print("Congratulations!") # Skipped too print("Your score was:", score) # This still runs - not indented
if-else: Two Paths
Often you want to do one thing if a condition is true and something different if it is false.
The else clause handles the "otherwise" case.
age = 16 if age >= 18: print("You can vote!") else: print("You are not old enough to vote yet.") years_left = 18 - age print(f"You can vote in {years_left} years.")
Real-World Example: Even or Odd
number = 7 if number % 2 == 0: print(f"{number} is even") else: print(f"{number} is odd")
if-elif-else: Multiple Conditions
When you have more than two possible paths, use elif (short for "else if") to
check additional conditions. Python checks them in order from top to bottom
and runs the first one that is True.
score = 82 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}")
True, it runs that block and skips all the rest.
If none are true, the else block runs (if there is one).
Real-World Example: Time of Day Greeting
hour = 14 if hour < 12: greeting = "Good morning!" elif hour < 17: greeting = "Good afternoon!" elif hour < 21: greeting = "Good evening!" else: greeting = "Good night!" print(greeting)
Multiple if vs. if-elif
An important distinction: multiple if statements each check independently,
while if-elif chains stop at the first match.
# Multiple separate if statements - ALL conditions are checked number = 15 if number > 5: print("Greater than 5") # Runs if number > 10: print("Greater than 10") # Also runs if number > 20: print("Greater than 20") # Does not run
# if-elif chain - stops at first True condition number = 15 if number > 5: print("Greater than 5") # Runs - and Python stops here elif number > 10: print("Greater than 10") # Skipped even though it's True! elif number > 20: print("Greater than 20") # Skipped
Use if-elif when the conditions are mutually exclusive (only one should run). Use multiple if statements when multiple conditions could be true simultaneously.
Common Patterns
Pattern 1: Validating User Input
user_input = input("Enter your age: ") if user_input.isdigit(): age = int(user_input) print(f"You are {age} years old.") else: print("That's not a valid age!")
Pattern 2: Min/Max Value
a = 15 b = 22 if a > b: larger = a else: larger = b print(f"The larger value is {larger}")
Pattern 3: Menu Selection
choice = "2" if choice == "1": print("Starting new game...") elif choice == "2": print("Loading saved game...") elif choice == "3": print("Opening settings...") else: print("Invalid choice. Please try again.")
Check Your Understanding
What will this code print?
x = 25 if x > 30: print("A") elif x > 20: print("B") elif x > 10: print("C") else: print("D")
Answer: B
Python checks top to bottom: 25 > 30 is False, so skip. 25 > 20 is True, so print "B" and skip the rest. Even though 25 > 10 is also True, it never gets checked because the elif chain already found a match.
Key Takeaways
ifruns code only when its condition isTrueelseprovides an alternative path when the condition isFalseelifchecks additional conditions in sequence- Always end
if,elif, andelselines with a colon: - Indentation defines which code belongs to which block
- In an if-elif chain, only the first
Truebranch runs