Lesson 6 of 30
In progress
Make decisions with if, elif and else
Write conditions that choose different paths, chain them with elif, and keep nested decisions readable instead of tangled.
A program that always does the same thing cannot be useful for long. The moment it checks a value and behaves differently, it can respond to a real person, a real score, or a real error.
What you will learn
- Write
if,elifandelseblocks with correct indentation. - Order conditions so the first true branch wins.
- Replace deep nesting with early exits.
A fork in the road
Imagine a railway junction. The train does not stop and think; the points are already set, and the train follows one track. An if statement is those points. Python checks a condition, and if it is true it runs one block and skips the rest.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
if score >= 50:
print("Pass")
else:
print("Try again")
Press Run to see the output.
The colon ends the condition. The indented lines belong to the branch. Four spaces is the convention, and mixing tabs with spaces is the fastest way to meet an IndentationError.
More than two paths
elif means "else, if". Python checks each condition in order and runs the first one that is true. Everything after it is skipped, even if it would also be true.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
if score >= 90:
print("Distinction")
elif score >= 75:
print("First class")
elif score >= 50:
print("Pass")
else:
print("Try again")
Press Run to see the output.
Order matters. If you checked score >= 50 first, a score of 95 would print "Pass" and never reach the distinction branch. Put the strictest condition first, or the one that must win.
else has no condition and is optional. Use it when there is a genuine catch-all case, not as a place to hide logic you have not thought through.
Conditions are just expressions
Anything that evaluates to true or false can be a condition. You can call a function, check membership, or combine comparisons.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
if name and is_member and visits > 2:
print("Welcome back, member")
Press Run to see the output.
An empty string, 0, an empty list and None are treated as false. Everything else is true. This is convenient, but explicit comparisons are clearer when a reader might not know the rule.
Nesting, and how to avoid it
A decision inside a decision works, but three levels deep becomes hard to read.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
if age >= 18:
if has_ticket:
print("Enter")
else:
print("Buy a ticket first")
else:
print("This event is for adults")
Press Run to see the output.
The flatter version below reaches the same result with early exits. Each branch ends the check, so the reader never carries a stack of conditions in their head.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
if age < 18:
print("This event is for adults")
elif not has_ticket:
print("Buy a ticket first")
else:
print("Enter")
Press Run to see the output.
Read that shape as a series of exits rather than a maze. The reader checks one condition at a time, and the main path sits at the left edge of the page. That is the guard-clause habit, and it scales to ten branches without becoming unreadable. Deep nesting is not wrong, but it makes a reader hold several conditions in their head at once, which is exactly when mistakes slip in.
Python 3.10 added match for comparing one value against several patterns. It reads well for menu choices, but if and elif remain the clearer tool while you are learning, because they show the order of checks explicitly. Choose the form a reader can follow, not the newest form.
Using = instead of == in a condition is a classic error. if score = 50: is a SyntaxError in Python, which is lucky, because in some languages it silently assigns. Write comparisons with two equals signs and read them aloud as "is equal to".
Ask for a temperature in Celsius and print one of four messages: "Freezing" below 0, "Cold" from 0 to 15, "Warm" from 16 to 30, and "Hot" above 30. Use elif and put the boundaries in a sensible order.
Show solution
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
if celsius < 0:
print("Freezing")
elif celsius <= 15:
print("Cold")
elif celsius <= 30:
print("Warm")
else:
print("Hot")
Press Run to see the output.
Because the branches are checked in order, celsius <= 15 only needs the upper bound: anything below 0 has already matched. This is why the order of elif branches matters.
Recap
ifruns a block when a condition is true;elifadds another check;elsecatches the rest.- Only the first true branch runs, so order conditions deliberately.
- Guard clauses reduce nesting and make the main path obvious.
Next, you will look closely at the comparisons and logical operators that decide which branch runs, including the cases where == surprises people.
Can I put an if statement on one line?
What does elif mean?
”Why
Progress is saved in this browser only. No account, no email.