What is a conditional?
So far, your programs have probably run straight down the page, one line after another. But real programs make decisions. A conditional statement lets your program ask a yes-or-no question and choose what to do based on the answer.
The question is always a boolean expression: something that works out to either True or False. Conditionals are called control structures because they control the flow of your program - which lines run, and which get skipped.
You already make decisions like this every day. Here is one through the eyes of a student:
"If I put in at least 2 hours of studying per weekday, I will increase my GPA."
There is a condition (studying at least 2 hours) and a result that only happens when the condition is met (the GPA goes up). That is exactly the shape of an if statement.
The if statement
An if statement works a lot like a hypothesis in science class: if a specific thing is true, then an expected result follows. In Python it has three parts:
if conditionmust be True or False:the colon starts the block statementindented body - runs only if the condition is True
- The condition is a boolean expression, like study_hours >= 2.
- The colon : at the end of the line tells Python a block of code is coming.
- The body is indented one level. Everything indented under the if belongs to it, and only runs when the condition is True.
Here is the studying example as a real program. Press Run to see what happens:
# The student studied 2 hours today study_hours = 2 # study_hours >= 2 is a boolean expression: it is True here if study_hours >= 2: print('Nice work, your GPA has increased!')
Nice work, your GPA has increased!
Heads up: if study_hours were 1, the condition would be False and the program would print nothing at all. The indented line simply gets skipped.
Comparison operators
To write a condition, you need a way to compare values. Python has six comparison operators, and every one of them produces True or False:
| Operator | Meaning | Example | Result |
|---|---|---|---|
| == | equal to | 5 == 5 | True |
| != | not equal to | 5 != 5 | False |
| < | less than | 3 < 7 | True |
| > | greater than | 3 > 7 | False |
| <= | less than or equal to | 2 <= 2 | True |
| >= | greater than or equal to | 1 >= 2 | False |
Classic mistake: one equals sign = assigns a value to a variable. Two equals signs == compare two values. Inside a condition, you almost always want ==.
Try it yourself. Pick two numbers and an operator, and watch Python's verdict update live:
Python reads 7 < 13 and answers True, so an if statement using this condition would run its body.
Adding else: a plan B
A lone if statement has one weakness: when the condition is False, nothing happens. In our study program, a student who studies 1 hour hears nothing back. What if we want the program to tell us whether the GPA goes up or down?
That is what else is for. It marks the other fork in the road, the path the program takes when the condition is False. In pseudocode:
- If the student studied at least 2 hours: print "GPA is increased"
- Else: print "GPA is not increased"
The else has no condition of its own. It simply means "otherwise", which keeps the code short - no need to write a second, opposite condition. Here is the program, now asking the user how long they studied:
# The study goal study_hours = 2 # Ask the user how many hours they studied user_input = int(input('Study Hours: ')) # Print the appropriate message if user_input >= study_hours: print('Nice work, your GPA has increased!') else: print('Sorry, your GPA has decreased.')
Study Hours: 1 Sorry, your GPA has decreased.
Exactly one path runs. With if/else, the program always picks one branch and never both. If the condition is True it takes the if path; otherwise it takes the else path.
Chaining with elif
Sometimes two paths are not enough. What if studying more than 2 hours raises the GPA, studying exactly 2 hours keeps it the same, and studying less lowers it? That is three outcomes, so we need a third branch: elif, short for "else if".
An elif adds another condition to check when the ones above it were False. You can chain as many as you need:
# The study goal study_hours = 2 # Ask the user how many hours they studied user_input = int(input('Study Hours: ')) # Print the appropriate message if user_input > study_hours: print('Nice work, your GPA has increased!') elif user_input == study_hours: print('Your GPA remains the same.') else: print('Sorry, your GPA has decreased.')
Study Hours: 2 Your GPA remains the same.
The rules of an if/elif/else chain:
- Python checks the conditions from top to bottom.
- The first condition that is True wins: its body runs, and the rest of the chain is skipped.
- If nothing is True, the else body runs (if there is one).
The decision machine
The best way to understand an elif chain is to watch Python walk through it. This program prices movie tickets by age. Pick an age with the slider, press Trace it, and watch each condition get checked in order until one wins:
age = 10if age < 5: print('Free ticket!')elif age < 13: print('Kids ticket: $6')elif age >= 65: print('Senior ticket: $8')else: print('Adult ticket: $12')
Pick an age, then press Trace it to watch the chain run.
Order matters! A 3-year-old is also less than 13, but they get the free ticket, not the kids ticket, because age < 5 is checked first. Once a condition wins, the rest of the chain never runs.
Combining conditions with and / or
Conditions can team up. The keywords and and or combine two boolean expressions into one:
- and is True only when both sides are True.
- or is True when at least one side is True.
sore_throat = True runny_nose = False # One symptom is enough to stay home if sore_throat or runny_nose: print('Rest up today!') # Both have to be True for this one if sore_throat and runny_nose: print('See the school nurse.')
Rest up today!
Only the first message prints: or is satisfied by the sore throat alone, but and needs both symptoms to be True.
Practice challenges
To recap: conditionals are control structures that steer your program between multiple outcomes. You have met the if statement, the if/else statement, the elif chain, booleans, and boolean expressions. Now put them to work! For each challenge, try writing the code yourself before peeking at a solution.
Hint: store the user's answer in a variable first, then compare it in your conditions.
Wellness App
Write a program that tells the user to make tea if they have a sore throat, or to grab tissues for a runny nose.
# Store the user's answer in a variable wellness = input("Do you have a sore throat? (Yes/No) ") if wellness == "Yes": print("Make tea.") else: print("Grab tissues for that runny nose.")
Do you have a sore throat? (Yes/No) Yes Make tea.
Fashion Guide
Ask the user to choose a season. Tell them which clothing item to order based on their input: Boots for Winter, Raincoat for Spring, Swimsuit for Summer, and Parka for Autumn.
season = input("Choose a season: ") if season == "Winter": print("Order boots.") elif season == "Spring": print("Order a raincoat.") elif season == "Summer": print("Order a swimsuit.") else: print("Order a parka.")
Choose a season: Summer Order a swimsuit.
The final else catches Autumn, but it would also catch a typo like "summre". A stricter version could use elif season == "Autumn": and save else for an error message.
Meal Planner
Ask the user for their dietary preference and print a lunch option: Grilled Seitan for Vegan, Seared Salmon for Pescatarian, Caprese Salad for Vegetarian, and Club Sandwich for None.
diet = input("Dietary preference (Vegan/Pescatarian/Vegetarian/None): ") if diet == "Vegan": print("Lunch: Grilled Seitan") elif diet == "Pescatarian": print("Lunch: Seared Salmon") elif diet == "Vegetarian": print("Lunch: Caprese Salad") else: print("Lunch: Club Sandwich")
Dietary preference (Vegan/Pescatarian/Vegetarian/None): Vegetarian Lunch: Caprese Salad
A grade checker
Conditionals let the program make decisions. This program turns a percentage into a letter grade.
Quick quiz
1. What does this program print?
age = 70 if age < 5: print('Free ticket!') elif age >= 65: print('Senior ticket') else: print('Adult ticket')
2. Which condition checks whether answer is exactly equal to 10?
3. In an if/elif/else chain, what happens when two conditions are both True?
Keep learning Python
Conditionals let your program choose a path once. Next, dig deeper into the booleans that power every condition, or learn while loops, which use a condition to repeat code again and again.