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.
temperature=28
iftemperature>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.
is_member=False
ifis_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.
score=82
ifscore>=90:
grade="A"
elifscore>=80:
grade="B"
elifscore>=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
age=20
has_id=True
ifage>=18andhas_id:
print("Allowed")
else:
print("Not allowed")
Option B (alternative): accept either condition with or
Python
is_admin=False
is_owner=True
ifis_adminoris_owner:
print("You can edit")
else:
print("Read-only")
Use not to invert a condition:
is_banned=False
ifnotis_banned:
print("Welcome")
5) Compare values the Python way
Most conditions use comparison operators:
==equal!=not equal<,>,<=,>=
Bash
country="US"
ifcountry=="US":
print("United States")
else:
print("Other")
For membership checks, use in:
role="editor"
allowed= {"admin","editor"}
ifroleinallowed:
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}
ifuser["active"]:
ifuser["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
value=125
ifvalue<0:
value=0
elifvalue>100:
value=100
print(value)
2) Parse simple command choices
Bash
choice="save"
ifchoice=="save":
print("Saving...")
elifchoice=="load":
print("Loading...")
else:
print("Unknown command")
3) Validate signup input
This checks conditions in order and stops at the first failure.
username="jo"
password="abc12345"
iflen(username)<3:
print("Username too short")
eliflen(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:
x=10
ifx =10:
print("Ten")
Why it breaks:
= assigns a value. Conditions need == to compare.
Correct approach:
x=10
ifx==10:
print("Ten")
Mistake 2: Forgetting the colon or indentation
You might write:
Bash
age=18
ifage>=18
print("Allowed")
Why it breaks:
Python uses : and indentation to define the block.
Correct approach:
age=18
ifage>=18:
print("Allowed")
Mistake 3: Writing impossible logic with or
You might write:
day="sat"
ifday=="sat"or"sun":
print("Weekend")
Why it breaks:
"sun" is always truthy, so the condition always passes.
Correct approach:
day="sat"
ifday=="sat"orday=="sun":
print("Weekend")
Or better:
Bash
ifdayin {"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 35M+ 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