Programs become interesting when they can make decisions. Should the game say "You win" or "Try again"? Is the password long enough? Is it a weekend? An if statement checks a condition and runs a block of code only when that condition is true.
Python's version is short and readable: if, optional elif (short for "else if") branches, and an optional else that catches everything else. The lines that belong to each branch are shown by indentation, the four spaces at the start of the line.
In this lesson you'll compare values, write if/elif/else chains, and combine conditions with and, or and not.
Comparison operators
A comparison asks a question and the answer is a boolean: True or False.
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | equal to | 5 == 5 | True |
!= | not equal to | 5 != 3 | True |
> / < | greater / less than | 7 > 9 | False |
>= / <= | greater or equal / less or equal | 18 >= 18 | True |
Don't confuse = and ==. One equals sign stores a value; two equals signs compare two values.
if, elif and else
temperature = 23
if temperature > 28:
print("It's hot. Drink water!")
elif temperature > 15:
print("Nice weather for a walk.")
else:
print("Take a jacket.")- Each condition line ends with a colon
:. - The lines underneath are indented by four spaces. They form the block for that branch.
- Python checks the conditions from top to bottom and runs only the first branch that's true. Here 23 isn't above 28, but it is above 15, so the second message prints.
elsehas no condition. It runs when none of the others matched.
Indentation is the block
Python doesn't use curly braces. Instead, every indented line under the if belongs to it, and the first line that goes back to the left edge is outside it:
if age >= 18:
print("You can vote.")
print("Remember to register.")
print("This line always runs.")Use four spaces per level. Most editors insert them automatically when you press Tab in a .py file.
and, or, not
andis true only when both sides are true.oris true when at least one side is true.notflips a boolean:not TrueisFalse.
has_ticket = True
age = 12
if has_ticket and age >= 12:
print("Enjoy the film!")You can also chain comparisons the way you would in maths: 13 <= age <= 19 checks whether someone is a teenager.
Truthy and falsy values
A condition doesn't have to be a comparison. Python can test any value directly, treating some values as false and everything else as true:
| Falsy values | Truthy examples |
|---|---|
False, None | True |
0, 0.0 | 1, -3, 0.5 |
"" (empty string) | "hello", " " |
[], {}, (), set() | [0], {"a": 1} |
This lets you write short, readable checks:
name = input("Name: ").strip()
if name:
print(f"Hello, {name}")
else:
print("You didn't type a name.")if name: is true for any non-empty string. Be careful when 0 is a valid value: if score: treats a score of 0 as "no score". In that case test explicitly with if score is not None:.
Nested ifs and one-line conditional expressions
An if can sit inside another if when the second question only makes sense after the first is answered:
logged_in = True
is_admin = False
if logged_in:
if is_admin:
print("Admin dashboard")
else:
print("Your account")
else:
print("Please log in")Deep nesting gets hard to follow, so combine conditions with and when you can.
For a simple choice between two values, Python has a conditional expression that fits on one line:
age = 15
ticket = "child" if age < 16 else "adult"
print(ticket) # childRead it as "child if age is under 16, otherwise adult". Use it for short value choices only; anything with several steps belongs in a normal if statement.
When a block is required but you have nothing to put in it yet, write pass. It does nothing, but keeps the indentation valid while you sketch out a program.
Python if Statements Syntax
if / elif / else
if condition:
# runs when condition is True
elif other_condition:
# runs when the first was False and this is True
else:
# runs when nothing above was TruePython if Statements Summary
- Comparisons such as
==,!=,>and<=giveTrueorFalse. if condition:runs its indented block only when the condition is true.elifadds more checks;elsecatches everything left over.- Only the first matching branch runs.
- Combine conditions with
and,orandnot.
Python if Statements Examples
Each example shows the code, the output it produces and what each part does.
Grade calculator
score = 78
if score >= 90:
grade = "A"
elif score >= 75:
grade = "B"
elif score >= 60:
grade = "C"
else:
grade = "Keep practising"
print(f"Score {score}: {grade}")Score 78: BLine-by-line explanation
- Line 378 is not 90 or more, so Python moves on.
- Line 578 is 75 or more, so grade becomes "B" and the rest of the chain is skipped.
- Line 12This line is not indented, so it runs whatever happened above.
Even or odd
number = 17
if number % 2 == 0:
print(f"{number} is even")
else:
print(f"{number} is odd")17 is oddLine-by-line explanation
- Line 3
%gives the remainder. Even numbers have a remainder of 0 when divided by 2. - Lines 5 to 6Only two possibilities, so a plain if/else is enough.
Combining conditions
day = "Saturday"
raining = False
is_weekend = day == "Saturday" or day == "Sunday"
if is_weekend and not raining:
print("Let's go to the park.")
elif is_weekend:
print("Board games at home.")
else:
print("School day.")Let's go to the park.Line-by-line explanation
- Line 4A comparison can be stored in a variable. is_weekend holds True.
- Line 6Both parts must be true: it's the weekend, and it's not raining.
- Line 8Only reached if the first test failed.
Common Python if Statements Mistakes
Using = instead of ==
if colour = "red":
print("Stop")if colour == "red":
print("Stop")A single = stores a value and isn't allowed in a condition, so Python shows a SyntaxError.
Forgetting the colon or the indent
if lives == 0
print("Game over")if lives == 0:
print("Game over")Every if, elif and else line needs a colon, and its block must be indented.
Checking the loose condition first
if score >= 50:
print("Pass")
elif score >= 90:
print("Excellent") # never reachedif score >= 90:
print("Excellent")
elif score >= 50:
print("Pass")Python if Statements in Real Projects
Decisions everywhere
Login screens check if password_is_correct, shops check if total >= 50 before removing the delivery charge, and games check if health <= 0 to end a level. Almost every feature you can think of contains at least one if statement.
Python if Statements FAQ
Does Python have a switch statement?
Python 3.10 added the match statement, which compares a value against several patterns and is the closest equivalent to switch. On older versions, and for simple range checks such as grades, an if/elif chain is the normal approach. A dictionary that maps keys to values also replaces many simple switches.
What is the difference between elif and several separate if statements?
In an if/elif chain, Python stops at the first true condition, so at most one branch runs. Separate if statements are each checked, so several of them can run. Use elif when the options are mutually exclusive, like grades, and separate ifs when each check is independent.
Can I write an if statement without an else?
Yes. else is optional. If the condition is false and there is no else, Python simply skips the block and carries on with the next unindented line.
How do I check if a value is one of several options?
Use in with a tuple or set instead of chaining or: if day in ("Saturday", "Sunday"):. A common bug is writing if day == "Saturday" or "Sunday":, which is always true because the non-empty string "Sunday" is truthy on its own.
Why do I get IndentationError in my if statement?
The lines inside an if block must all be indented by the same amount, usually four spaces, and the block can't be empty. Mixing tabs and spaces also causes this error. Set your editor to insert spaces when you press Tab, and use pass as a placeholder for an empty block.
Python if Statements Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
Complete the code so it prints "Too cold" when temp is below 10, and "OK" otherwise.
temp = 4
temp < 10:
print("Too cold")
:
print("OK")
What does this print?
x = 10
if x > 5:
print("big")
elif x > 8:
print("bigger")
else:
print("small")
Which condition is True when age is between 13 and 19, inclusive?
What does this print?
logged_in = False
is_admin = True
if logged_in and is_admin:
print("Admin panel")
elif not logged_in:
print("Please log in")
else:
print("Welcome")
What does this print?
age = 15
if age >= 18:
print("adult")
elif age >= 13:
print("teen")
elif age >= 5:
print("child")
Python if Statements Quiz
5 questions to check what you learned.
What does
==do in Python?- Stores a value
- Checks whether two values are equal
- Checks whether two values are different
- Joins two strings
What must come at the end of an
ifline?- A semicolon
- Curly braces
- Nothing
- A colon
How many branches of an if/elif/else chain can run at once?
- All the true ones
- Exactly two
- At most one
- It depends on the indentation
What is the value of
not (5 > 3 and 2 > 4)?- True
- False
- None
- An error
What does
not (5 > 3)evaluate to?- False
- True
- 5
- An error