How to Use if else in Python
What you’ll build or solve
You’ll write if, elif, and else blocks that make decisions based on conditions.
When this approach works best
This approach works best when you:
Learn Python on Mimo
- Validate input before you use it, like checking a number is in range.
- Choose between actions, like showing a different message for new vs returning users.
- Handle multiple outcomes, like grading scores or mapping status codes to labels.
Prerequisites
- Python 3 installed
- You know what variables are
- You can run a
.pyfile or use the Python REPL
Step-by-step instructions
1) Write a basic if block
An if block runs only when its condition is true.
Python
temperature = 28
if temperature > 25:
print("It is warm")
2) Add an else for the fallback case
Use else when you want a default path if the condition is false.
Python
is_member = False
if is_member:
price = 8
else:
price = 10
print(price)
What to look for:
- The condition after
ifmust be followed by:. - The block must be indented.
3) Use elif for multiple conditions
Use elif when you have more than two branches.
Python
score = 82
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "D"
print(grade)
Python checks each condition in order and stops at the first one that is true.
4) Combine conditions with and, or, and not
You can build more precise checks by combining boolean logic.
Option A (most common): require multiple conditions with and
Python
age = 20
has_id = True
if age >= 18 and has_id:
print("Allowed")
else:
print("Not allowed")
Option B (alternative): accept either condition with or
Python
is_admin = False
is_owner = True
if is_admin or is_owner:
print("You can edit")
else:
print("Read-only")
Use not to invert a condition:
Python
is_banned = False
if not is_banned:
print("Welcome")
5) Compare values the Python way
Most conditions use comparison operators:
==equal!=not equal<,>,<=,>=
Python
country = "US"
if country == "US":
print("United States")
else:
print("Other")
For membership checks, use in:
Python
role = "editor"
allowed = {"admin", "editor"}
if role in allowed:
print("Access granted")
What to look for:
Use == for equality checks. A single = is for assignment.
6) Use nested if blocks when you need a second decision
Nesting works when one decision depends on another. Keep nesting shallow so your code stays readable.
Python
user = {"name": "Sam", "active": True}
if user["active"]:
if user["name"]:
print("Active user with a name")
else:
print("Active user missing a name")
else:
print("Inactive user")
Examples you can copy
1) Clamp a number into a range
Python
value = 125
if value < 0:
value = 0
elif value > 100:
value = 100
print(value)
2) Parse simple command choices
Python
choice = "save"
if choice == "save":
print("Saving...")
elif choice == "load":
print("Loading...")
else:
print("Unknown command")
3) Validate signup input
This checks conditions in order and stops at the first failure.
Python
username = "jo"
password = "abc12345"
if len(username) < 3:
print("Username too short")
elif len(password) < 8:
print("Password too short")
else:
print("Looks good")
Common mistakes and how to fix them
Mistake 1: Using = instead of == in a condition
You might write:
Python
x = 10
if x = 10:
print("Ten")
Why it breaks:
= assigns a value. Conditions need == to compare.
Correct approach:
Python
x = 10
if x == 10:
print("Ten")
Mistake 2: Forgetting the colon or indentation
You might write:
Python
age = 18
if age >= 18
print("Allowed")
Why it breaks:
Python uses : and indentation to define the block.
Correct approach:
Python
age = 18
if age >= 18:
print("Allowed")
Mistake 3: Writing impossible logic with or
You might write:
Python
day = "sat"
if day == "sat" or "sun":
print("Weekend")
Why it breaks:
"sun" is always truthy, so the condition always passes.
Correct approach:
Python
day = "sat"
if day == "sat" or day == "sun":
print("Weekend")
Or better:
Python
if day in {"sat", "sun"}:
print("Weekend")
Troubleshooting
If you see IndentationError, check that you used consistent indentation, usually 4 spaces, inside the if block.
If you see SyntaxError at the if line, check for a missing : at the end of the condition.
If your if block never runs, print the values you compare and confirm types match, like "10" (string) vs 10 (int).
If a condition seems backwards, rewrite it with a simpler comparison first, then add and or or after it works.
Quick recap
- Use
iffor a single condition, andelsefor the fallback. - Use
eliffor multiple branches. - Combine checks with
and,or, andnot. - Use
==for comparisons, andinfor membership checks. - Watch colons and indentation, Python treats them as syntax.
Join 40M+ people learning for free on Mimo
4.8 out of 5 across 1M+ reviews
Check us out on Apple AppStore, Google Play Store, and Trustpilot