In Part 3 we learned how to compare and combine values with operators. A comparison always hands back True or False — and that's exactly what we need to make a program make decisions.
That's what conditional statements are for. They let your code run one piece of logic when something is true, and a different piece when it isn't. If you followed the PHP series, this is the same idea — but Python drops the braces and leans on the indentation we met back in Part 1. Let me walk you through it.
The if Statement
The simplest decision. You give if a condition, end the line with a colon :, and indent the code that should run only when that condition is true:
age = 20
if age >= 18:
print("You are an adult.")
Notice two things that are very Python:
- No parentheses are needed around the condition (you can add them, but they're just clutter).
- No braces. Where PHP wraps the body in
{ }, Python uses the colon plus an indented block. Everything indented under theifbelongs to it; the first line that dedents is back outside.
Because age is 20, the condition age >= 18 is true, so the message prints. If age were 15, the condition would be false and nothing would happen.
Adding an else
Usually you want a fallback — something to do when the condition is not true. That's what else is for:
age = 15
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
Here the condition is false, so the else block runs and we get "You are a minor." One of the two blocks always runs — never both. Note that else gets its own colon and indented block, and lines up vertically with the if.
Testing Several Cases with elif
What if there are more than two possibilities? Chain them with elif — Python's shorthand for "else if" (PHP spells it elseif, one word; JavaScript uses two). Python checks each condition from top to bottom and runs the first one that's true:
score = 82
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: F")
A score of 82 fails the first test (>= 90) but passes the second (>= 80), so we get "Grade: B" — and Python stops there, never checking the rest. The order matters: put your tightest conditions first.
Note: you can have as many elif branches as you like, and the final else is optional. There's no switch keyword in Python — elif is the everyday tool for multi-way choices (though newer Python adds match, which we'll meet at the end).
Nesting Conditions
You can place an if inside another if when a decision depends on a previous one — just indent one level deeper:
logged_in = True
is_admin = False
if logged_in:
if is_admin:
print("Welcome, admin.")
else:
print("Welcome, user.")
else:
print("Please log in.")
Nesting is fine in small doses, but once you're three or four levels deep the indentation marches off to the right and the logic gets hard to follow. Often the logical operators (and, or) from Part 3 can flatten it — if logged_in and is_admin: says the same thing as the nested check above, in one line.
A Quick Word on Truthiness
Python will happily evaluate values that aren't strictly True/False inside a condition. The number 0, an empty string "", an empty list [], and None all count as falsy; most other values — any non-zero number, any non-empty string or list — count as truthy. So this works:
name = ""
if name:
print(f"Hello, {name}!")
else:
print("No name given.")
The empty string is falsy, so we get "No name given." This is the Pythonic way to ask "is there anything here?" — if items: reads more naturally than if len(items) > 0:. It's a handy shortcut, but be aware of it: a 0 or an empty string slipping into a condition is a common source of surprises.
Note: to check specifically for "no value", compare against None with is — if result is None: — the habit we picked up in Part 3. That's different from falsy: 0 and "" are falsy but they are not None.
The Ternary Shortcut
For a simple "if this, then A, else B" you can write it all on one line. Python's version reads almost like a sentence — the value comes first, then the condition:
age = 20
status = "adult" if age >= 18 else "minor"
print(status) # adult
Read it as: "use 'adult' if age >= 18, otherwise 'minor'." It's officially called a conditional expression. Handy for short assignments — but don't overuse it, because long ones get hard to read fast. When it stops fitting comfortably on one line, go back to a normal if/else.
Matching Many Cases with match (Python 3.10+)
When you're checking one value against several fixed options, a long elif chain gets repetitive. Since Python 3.10, there's a cleaner tool — the match statement — which plays a role similar to switch in other languages:
command = "start"
match command:
case "start":
print("Starting up...")
case "stop":
print("Shutting down...")
case _:
print("Unknown command.")
A few things to notice:
- Each
caseis one value to comparecommandagainst, and only the matching block runs. - There's no fall-through to worry about — unlike PHP's
switch, Python runs only the matched case, so you never need abreak. case _:is the catch-all (the underscore is a wildcard), like a finalelse.
Note: match only exists in Python 3.10 and newer — check your version with python3 --version. If you're on an older Python, stick with an elif chain, which works everywhere. (match can actually do far more than this — destructuring tuples, objects, and more — but value-matching is the part you'll reach for first.)
To Be Continued…
You can now make your programs branch and decide — if/elif/else for the everyday choices, the one-line ternary for the tiny ones, and match when you're checking a single value against many. Combined with the operators from Part 3, that's already enough to write genuinely useful logic.
In Part 5 we'll cover Loops — for, while, and range() — so your code can repeat work without you copy-pasting it a hundred times. Stay tuned!