Conditional Branching
Make decisions with if/elif/else statements. Read the lesson first, then move through the exercises in order.
After reading
Practice Arena
Begin with the first exercise, then continue step by step through the module.
Start with Even or OddStudy Material
Read the full lesson
Making decisions
Programs would be incredibly boring if they just did the exact same thing every single time they ran.
To write intelligent software, your code needs to make decisions based on changing conditions.
We do this using if, elif, and else statements.
The basic if statement
An if statement checks a Boolean condition. If it is True, the indented code underneath it runs. If it is False, Python skips over it entirely.
pythontemperature = 35 if temperature > 30: print("It's a hot day!") print("Drink plenty of water.")
Because 35 is greater than 30, both print statements will execute. Notice that the code inside the block must be indented (this is usually done with 4 spaces).
Expanding with else
What if you want something to happen when the condition is False? Use else.
pythonpassword = "123" if password == "secret": print("Access granted.") else: print("Access denied!")
The else block catches everything that fails the if test.
Chaining with elif
If you have more than two possibilities, you can use elif (short for "else if").
Python will check them back-to-back until it finds one that is True.
pythonscore = 85 if score >= 90: print("Grade: A") elif score >= 80: print("Grade: B") elif score >= 70: print("Grade: C") else: print("Grade: F")
Here, Python checks score >= 90 (False). Then it checks score >= 80 (True!). It prints "Grade: B" and immediately exits the entire chain. It never bothers checking the C or F conditions.
What this lesson should give you
After this lesson, you should understand how to:
- write an
ifstatement to run code conditionally - use
elseas a fallback option - chain multiple conditions sequentially using
elif - properly indent code blocks to tell Python which lines belong to the statement
Interactive
Exercises for this topic
These exercises follow the exact order of the lesson. Move step-by-step from reading into coding.
Even or Odd
Complete the "Even or Odd" exercise.
Grade Calculator
Complete the "Grade Calculator" exercise.
Maximum of Three
Complete the "Maximum of Three" exercise.
Ticket Price by Age
Complete the "Ticket Price by Age" exercise.
Vowel or Consonant
Complete the "Vowel or Consonant" exercise.