if Statements
Run different code depending on what's true
In this lesson
An if statement lets your program choose what to do: it runs a block of code only when a condition is true, and optionally does something else otherwise. It’s how Python makes decisions instead of running every line top to bottom.
Explain it like I’m 5
An if is a fork in the road. Python checks a question that’s either yes or no, and only walks down the path that matches the answer.
The shape of an if statement
An if statement has a condition — an expression that evaluates to True or False — followed by a colon, then an indented block of code that runs only when the condition is true.
The indentation isn’t decoration: in Python it’s how you mark which lines belong to the if. Every line indented the same amount under the colon is ‘inside’ the block. When the indentation stops, the block ends.
temperature = 30
if temperature > 25:
print("It is warm.")
print("Wear something light.")
print("Have a good day.")
It is warm. Wear something light. Have a good day.
elif and else: covering the other cases
else runs when the if condition was false. elif (‘else if’) lets you test another condition only if the previous ones failed. Python checks them top to bottom and runs the first block whose condition is true — then skips the rest.
Use a plain if when conditions are independent (each should be checked). Use elif chains when exactly one branch should win.
age = 17
if age >= 18:
print("You can vote.")
elif age >= 16:
print("Almost there.")
else:
print("Still a few years to go.")
Almost there.
Change score and run it. Try values above 90, between 60 and 90, and below 60 to hit each branch.
score = 75
if score >= 90:
print("Grade: A")
elif score >= 60:
print("Grade: Pass")
else:
print("Grade: Try again")
Only the first matching branch runs. To see 'Grade: A', score must be 90 or more.
score = 95
if score >= 90:
print("Grade: A")
elif score >= 60:
print("Grade: Pass")
else:
print("Grade: Try again")
Grade: Pass
What counts as a condition
Conditions are usually built from comparisons: == (equal), != (not equal), <, >, <=, >=. You combine them with and, or, and not. and is true only if both sides are true; or is true if either side is.
Watch the difference between = (assigns a value) and == (asks whether two values are equal). Using = in a condition is a common slip and Python will flag it.
temperature = 30
is_raining = False
if temperature > 25 and not is_raining:
print("Great day for a walk.")
Great day for a walk.
Truthiness: values that act like True or False
basket = []
if basket:
print("Ready to check out.")
else:
print("Your basket is empty.")
Your basket is empty.
Nesting conditions (and keeping them shallow)
An if can live inside another if — a nested condition that’s only checked once an outer one has passed. It’s useful, but deep nesting quickly gets hard to follow, so keep it shallow: often an and or an early elif reads better than a second level of indentation.
When you only need to choose a value rather than run different code, the one-line conditional expression is tidier — that’s covered under operators.
attended = True
score = 85
if attended:
if score >= 60:
print("Passed")
else:
print("Retake needed")
else:
print("Did not attend")
Passed
Common mistake: Using = instead of == in a condition
= means ‘assign’, but it’s easy to type it when you mean ‘compare’. Python raises a SyntaxError for if x = 5:.
Use == to compare: if x == 5:. Reserve a single = for setting a variable’s value.
if x == 5:
print("x is five")
Common mistake: Forgetting the colon or the indentation
The : ends the condition and the indented block defines what runs. Leaving either out breaks the structure Python expects.
End the if line with : and indent the body by four spaces.
In an if/elif/else chain, how many branches run?
Python runs the first matching branch and skips the rest of the chain.
Which operator checks whether two values are equal?
== compares; a single = assigns a value.
Mini exercise (easy)
Set a variable hour (0–23) and print ‘Good morning’ before 12, ‘Good afternoon’ from 12 to 17, and ‘Good evening’ otherwise.
Do it here. Finish the code below and press Run to try your answer right in the browser — no setup needed.
def greeting(hour):
# return "Good morning" (<12), "Good afternoon" (12-17), else "Good evening"
return "Good morning"
print(greeting(9))
Use if hour < 12:, then elif hour < 18:, then else.
def greeting(hour):
if hour < 12:
return "Good morning"
elif hour < 18:
return "Good afternoon"
else:
return "Good evening"
print(greeting(9))
assert greeting(9) == "Good morning", "hour 9 should give Good morning"
assert greeting(13) == "Good afternoon", "hour 13 should give Good afternoon"
assert greeting(20) == "Good evening", "hour 20 should give Good evening"
print("✓ All times handled!")