Control Flow — Decisions, Loops & Comprehensions
if/elif/else for decisions, for x in things: to loop, while for "until done", and list comprehensions to build new lists in one readable line.if / elif / else
Same idea as PHP, cleaner spelling. The keyword is elif (not else if or elseif), and every branch ends in a colon with an indented body.
score = 82
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print(grade) # B
The comparison operators are the familiar set: == != < > <= >=. Combine conditions with the words and, or, not — not the && || ! symbols you'd use in PHP. Python deliberately spells them out for readability.
if revenue > target and not on_holiday:
print("Push for the stretch goal")
🐘 PHP: Three swaps to remember: elseif → elif, && → and, || → or. And there's no switch in older Python; you use elif chains (or match in 3.10+, which you'll rarely need at first).
Truthiness — what counts as "empty"
Python treats a handful of values as "falsy": False, 0, 0.0, "" (empty string), [] (empty list), {} (empty dict), and None. Everything else is "truthy." This lets you write the very natural-reading idiom:
orders = []
if not orders:
print("No orders to process") # this runs — empty list is falsy
🐘 PHP: Very close to PHP's truthiness, with one big mercy: "0" (the string zero) is truthy in Python, whereas in PHP it's falsy and bites people constantly. And there's no loose == type-juggling madness — 0 == "0" is just False in Python.
The for loop — iterate over things directly
Python's for loops over the items of a collection, not over a counter. You almost never write for (i = 0; i < n; i++).
regions = ["North", "South", "East", "West"]
for region in regions:
print(f"Processing {region}")
Need the index too? Wrap the collection in enumerate():
for i, region in enumerate(regions):
print(f"{i}: {region}")
And when you genuinely need a counter (say, "do this 5 times"), use range():
for n in range(5): # 0,1,2,3,4
print(n)
for n in range(1, 6): # 1,2,3,4,5 (start, stop — stop is excluded)
print(n)
🐘 PHP: foreach ($regions as $region) becomes for region in regions:. PHP's foreach ($arr as $k => $v) has two Python equivalents depending on the shape: enumerate() for list index+value, and .items() for dict key+value (next chapter).
while, break, continue
while repeats until its condition goes false. break bails out of the loop entirely; continue skips to the next iteration. Identical meanings to PHP.
attempts = 0
while attempts < 3:
attempts += 1
if attempts == 2:
continue # skip the rest of this pass
print(f"Attempt {attempts}")
++: Python has no ++ or --. Use attempts += 1. The compound operators += -= *= /= all work as you'd expect.The comprehension — your new favourite tool
This is the one to internalise. A list comprehension builds a new list by transforming (and optionally filtering) an existing one, in a single expressive line. It's the Pythonic replacement for "make an empty list, loop, append."
prices = [10, 25, 40, 8, 100]
# transform: add 15% tax to every price
with_tax = [p * 1.15 for p in prices]
# filter: keep only the big-ticket items
big = [p for p in prices if p >= 40]
# transform + filter together
discounted_big = [p * 0.9 for p in prices if p >= 40]
Read it left to right as a sentence: "p times 1.15, for each p in prices." Once this clicks, you'll reach for it dozens of times a day — cleaning columns, reshaping records, pulling fields out of data. It's faster than a manual loop and, more importantly, it states intent instead of mechanics.
There's a dict version too, which you'll use to remap data:
names = ["north", "south", "east"]
lookup = {name: len(name) for name in names}
# {'north': 5, 'south': 5, 'east': 4}
🐘 PHP: PHP has no direct equivalent — the closest is array_map() + array_filter(), but those need callbacks and read awkwardly. The comprehension does both jobs in one line you can actually read aloud. This is a genuine quality-of-life upgrade over the PHP way.
Classify the Customers
Goal: turn a list of raw spend numbers into business segments using a loop and a comprehension — the exact shape of work you'll automate with pandas later.
- Start with the data:
spend = [120, 5400, 880, 30, 2100, 45] - Write a function-free classifier with a comprehension:
tiers = ["VIP" if s >= 2000 else "Regular" if s >= 500 else "Low" for s in spend] - Pair each number with its tier and print it:
for amount, tier in zip(spend, tiers): print(f"${amount:>5,} -> {tier}") - Count the VIPs in one line:
vips = len([t for t in tiers if t == "VIP"])
You just met zip() (pairs up two lists item-by-item) and a conditional expression inside a comprehension. That's a lot of real analytics power in four lines.
if/elif/else, loop over data with for, repeat with while, and — the big one — reshape entire lists with comprehensions. This is the muscle you'll flex on every dataset.
for loop, and .append() each tier manually. Then look at both versions side by side. Same result — but feel how the comprehension says what you want while the loop spells out how. That instinct for "is there a one-liner?" is what makes Python feel good.