Table of Contents
The Basic `if` Statement
In this chapter, you’ll focus on how to use if, elif, and else to control which parts of your code run.
A basic if statement checks a condition and runs a block of code only if that condition is True.
age = 20
if age >= 18:
print("You are an adult.")How it works:
age >= 18is a condition (a comparison that results inTrueorFalse).- The line under
ifis indented (by 4 spaces here).
Indentation tells Python which lines belong to theifblock. - If the condition is
False, the indented code is skipped.
You can have any number of lines inside the if block:
age = 20
if age >= 18:
print("You are an adult.")
print("You can enter the website.")
print("Enjoy your stay!")
All three print lines run only if age >= 18 is True.
Adding an `else` Block
else is used when you want to run alternative code if the if condition is False.
age = 15
if age >= 18:
print("You are an adult.")
else:
print("You are not an adult.")How it works:
- Python checks
if age >= 18. - If it’s
True, only theifblock runs. - If it’s
False, theelseblock runs instead. - Exactly one of the two blocks (
iforelse) will run.
More realistic example:
temperature = 30
if temperature > 25:
print("It's warm outside.")
else:
print("It's not very warm today.")Multiple Choices with `elif`
Sometimes there are more than two possibilities.
That’s what elif is for: “else if”.
Basic pattern:
if condition1:
# code if condition1 is True
elif condition2:
# code if condition2 is True and condition1 was False
elif condition3:
# code if condition3 is True and all above were False
else:
# code if none of the conditions were TrueExample: grading system
score = 72
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
elif score >= 60:
print("Grade: D")
else:
print("Grade: F")Important details:
- Python checks the conditions top to bottom.
- As soon as it finds a
Truecondition, it runs that block and skips the rest. - Only one block among
if/elif/elseruns.
In the example above:
- If
scoreis 95 →score >= 90isTrue→ prints"Grade: A"→ done. - If
scoreis 85 →score >= 90isFalse,score >= 80isTrue→ prints"Grade: B"→ done. - If
scoreis 40 → allif/elifconditions areFalse→elseruns.
When to Use `if`, `elif`, and `else`
Some common patterns:
`if` only
Use if alone when you only care about one situation and don’t need an “otherwise”.
age = 19
if age >= 18:
print("You can vote.")
If the condition is False, nothing happens.
`if` + `else`
Use if + else when there are two exclusive options.
number = 3
if number % 2 == 0:
print("Even")
else:
print("Odd")This guarantees one of the two messages is printed.
`if` + `elif` (+ `else`)
Use if + elif when you have several possible categories.
hour = 14
if hour < 12:
print("Good morning")
elif hour < 18:
print("Good afternoon")
else:
print("Good evening")Here:
- If
hour < 12: morning - Else if
hour < 18: afternoon - Else: evening
Execution Order and “First Match” Rule
With if–elif–else chains, remember:
- Conditions are checked in order, from top to bottom.
- The first condition that is
Trueis chosen. - After that block runs, the rest of the chain is ignored.
Example:
x = 10
if x > 0:
print("Positive")
elif x > 5:
print("Greater than 5")
Even though x > 5 is True, you will only see:
PositiveBecause:
x > 0is checked first and isTrue, so"Positive"is printed.- The
elif x > 5is never checked.
To make the second condition work as intended, you’d have to reorder them:
x = 10
if x > 5:
print("Greater than 5")
elif x > 0:
print("Positive")Now the output is:
Greater than 5Attaching `else` to the Right `if`
An else (and elif) always belongs to the nearest previous if that doesn’t already have an else.
Correct example:
age = 17
if age >= 18:
print("Adult")
else:
print("Minor")Incorrect structure (common confusion):
# This is valid Python, but maybe not what you intended:
age = 17
if age >= 18:
if age >= 21:
print("You can drink alcohol (in some countries).")
else:
print("You are under 18.")
Here, the else is paired with the inner if age >= 21, not the outer one.
So "You are under 18." only runs if age >= 18 is True and age >= 21 is False.
In other words:
- If
age = 17→ outerifisFalse→ nothing runs. - If
age = 19→ outerifisTrue, innerifisFalse→"You are under 18."prints (which is wrong logically).
You usually want this instead:
age = 17
if age >= 18:
if age >= 21:
print("You can drink alcohol (in some countries).")
else:
print("You are an adult, but cannot drink alcohol yet.")
else:
print("You are under 18.")
Notice how indentation makes it clear which else belongs to which if.
Writing Clear Conditions
You can often simplify and clarify your if / elif / else blocks.
Avoid overlapping conditions
Example with overlapping:
score = 85
if score >= 70:
print("Pass")
elif score >= 80:
print("Good")
Here, "Good" will never print, because if score >= 80, then score >= 70 is also True, and the first condition already matches.
Better:
score = 85
if score >= 80:
print("Good")
elif score >= 70:
print("Pass")Use `elif` instead of multiple separate `if`s (when appropriate)
Sometimes beginners write:
temperature = 10
if temperature < 0:
print("Freezing")
if temperature < 15:
print("Cold")
if temperature < 25:
print("Mild")
If temperature = 10, all three messages except "Freezing" will print, which might not be what you want.
To choose exactly one category, use elif and else:
temperature = 10
if temperature < 0:
print("Freezing")
elif temperature < 15:
print("Cold")
elif temperature < 25:
print("Mild")
else:
print("Warm")Now only one message is printed.
Common Pitfalls with `if` / `elif` / `else`
1. Forgetting the colon `:`
Every if, elif, and else line must end with :.
if age >= 18:
print("Adult")
elif age >= 13:
print("Teen")
else:
print("Child")
If you miss a colon, you’ll get a SyntaxError.
2. Mixing up `==` and `=`
=is for assignment (storing a value in a variable).==is for comparison (checking equality in conditions).
Incorrect:
if x = 10: # Error!
print("x is 10")Correct:
x = 10
if x == 10:
print("x is 10")3. Indentation mistakes
Blocks under if, elif, and else must be consistently indented.
Incorrect:
age = 20
if age >= 18:
print("Adult") # Not indented → errorCorrect:
age = 20
if age >= 18:
print("Adult")Or with multiple lines:
age = 20
if age >= 18:
print("Adult")
print("Welcome!")All lines in the block must be indented the same amount.
Small Practice Ideas
Here are a few small programs you can try to write using if, elif, and else:
- Day of the week greeting
- Ask the user to enter a number from 1 to 7.
- If 1 → print
"Monday", if 2 →"Tuesday", …, if 7 →"Sunday". - Use
if/elif/elseto handle it. - Ticket price based on age
- If age < 3 →
"Free". - If age is 3–12 →
"Child ticket". - If age is 13–64 →
"Adult ticket". - If age is 65 or older →
"Senior ticket". - Simple login check
- Store a correct password in a variable.
- Ask the user to input a password.
- If it matches →
"Access granted", else →"Access denied".
As you practice, pay attention to:
- Using
ifwhen you only need a single check. - Adding
elsewhen you need an “otherwise”. - Adding
elifwhen you have several categories. - The order of your conditions and how it affects which block runs.