Real programs need to react to different situations. A game needs to check whether the player has won. A login page needs to check whether the password is correct. A weather app needs to decide what to display based on temperature. All of these decisions use if-else statements — one of the most important ideas in all of programming.
The if Statement
The simplest decision just checks whether something is true:
temperature = 30
if temperature > 25:
print("It's a hot day!")
If the condition temperature > 25 is True, the indented block runs. If it is False, Python skips the block entirely.
Adding else
else provides an alternative block that runs when the condition is False:
temperature = 18
if temperature > 25:
print("It's a hot day!")
else:
print("It's not that warm today.")
Only one of the two blocks will ever run — they are mutually exclusive.
Indentation is how Python knows which lines belong to the if block and which belong to else. Always use 4 spaces (or one Tab). Mixing spaces and tabs causes errors.
Adding More Choices with elif
When you have more than two possibilities, use elif (short for "else if") to chain conditions:
score = 75
if score >= 90:
print("Grade: A")
elif score >= 70:
print("Grade: B")
elif score >= 50:
print("Grade: C")
else:
print("Grade: F")
Python checks each condition from top to bottom and runs the first block whose condition is True. Once a match is found, all remaining elif and else blocks are skipped.
Comparison Operators
To write conditions you need comparison operators:
| Operator | Meaning | Example |
|---|---|---|
== | Equal to | x == 5 |
!= | Not equal to | x != 5 |
> | Greater than | x > 3 |
< | Less than | x < 10 |
>= | Greater than or equal | x >= 18 |
<= | Less than or equal | x <= 100 |
A very common mistake: using = instead of == inside a condition. if x = 5: will cause a SyntaxError. Assignment uses =, comparison uses ==.
Nested If Statements
You can place an if statement inside another if block:
is_member = True
age = 16
if is_member:
if age >= 18:
print("Full membership benefits.")
else:
print("Junior member benefits.")
else:
print("Please join to access benefits.")
Keep nesting shallow — more than two or three levels deep is usually a sign you can restructure using elif or logical operators.
A Practical Example
username = input("Username: ")
password = input("Password: ")
if username == "admin" and password == "pass123":
print("Login successful.")
elif username == "admin":
print("Wrong password.")
else:
print("Unknown user.")
Practice Problems
How many blocks will run in an if-elif-elif-else chain? Explain your answer.
Show answer
A student writes: if x = 10: print('ten'). What is wrong and how do they fix it?