Python Zero to Advanced #3: Conditionals and Loops
So far our programs have run every line exactly once, from top to bottom. Real programs need to make decisions (show a discount only for members) and repeat work (send an email to every customer). In this part we cover Python's control flow: if, for, and while.
if, elif, else
An if statement runs its indented block only when the condition is truthy. Add elif (else if) for more branches and else as the fallback. Python checks the branches in order and runs only the first one that matches.
def grade(score):
if score >= 85:
return "A"
elif score >= 70:
return "B"
elif score >= 55:
return "C"
else:
return "D"
for s in [92, 85, 71, 40]:
print(s, "->", grade(s))
Output:
92 -> A
85 -> A
71 -> B
40 -> D
We wrapped the logic in a small function so we can test several scores; functions get their own part later. The important thing is the colon after each condition and the four-space indentation of each block.
Truthiness and combined conditions
cart = []
user = {"name": "Budi", "is_member": True}
if not cart:
print("Your cart is empty")
if user["is_member"] and len(cart) == 0:
print("Members get free shipping on the first order")
age = 17
status = "adult" if age >= 18 else "minor" # ternary expression
print(status)
Output:
Your cart is empty
Members get free shipping on the first order
minor
if not cart is the idiomatic way to check for an empty list. The one-line conditional expression a if condition else b is handy for simple assignments, but avoid nesting it.
match (Python 3.10+)
For comparing one value against many fixed options, Python 3.10 introduced match:
def http_message(code):
match code:
case 200:
return "OK"
case 404:
return "Not Found"
case 500 | 502 | 503:
return "Server Error"
case _:
return "Unknown"
print(http_message(404))
print(http_message(502))
print(http_message(418))
Output:
Not Found
Server Error
Unknown
for loops
A for loop iterates over any iterable: a list, a string, a dictionary, a file, and more. Each iteration binds the next item to the loop variable.
names = ["Budi", "Siti", "Andi"]
for name in names:
print(f"Hello, {name}")
for ch in "abc":
print(ch.upper(), end=" ")
print()
for i, name in enumerate(names, start=1):
print(i, name)
Output:
Hello, Budi
Hello, Siti
Hello, Andi
A B C
1 Budi
2 Siti
3 Andi
Use enumerate() when you need both the index and the item, instead of manually maintaining a counter. To walk two lists in parallel, use zip():
products = ["Coffee", "Tea", "Juice"]
prices = [18000, 12000, 15000]
for product, price in zip(products, prices):
print(f"{product:<7}{price:>7,}")
Output:
Coffee 18,000
Tea 12,000
Juice 15,000
range()
range() produces a sequence of integers lazily. It takes start (inclusive, default 0), stop (exclusive), and an optional step.
print(list(range(5)))
print(list(range(2, 8)))
print(list(range(0, 20, 5)))
print(list(range(5, 0, -1)))
total = 0
for n in range(1, 101):
total += n
print("Sum 1..100 =", total)
Output:
[0, 1, 2, 3, 4]
[2, 3, 4, 5, 6, 7]
[0, 5, 10, 15]
[5, 4, 3, 2, 1]
Sum 1..100 = 5050
Remember that stop is never included: range(1, 101) gives 1 through 100.
while loops, break, continue
A while loop repeats as long as its condition stays truthy. It is the right tool when you do not know in advance how many iterations you need.
balance = 1_000_000
month = 0
while balance < 1_500_000:
balance = int(balance * 1.05) # 5% growth per month
month += 1
print(f"Reached {balance:,} after {month} months")
Output:
Reached 1,551,325 after 9 months
break exits the loop immediately; continue skips to the next iteration. Loops also support an else block, which runs only if the loop finished without hitting break. It is perfect for search loops.
for n in range(1, 11):
if n % 2 == 0:
continue # skip even numbers
if n > 7:
break # stop completely
print(n, end=" ")
print()
emails = ["budi@example.com", "siti@example.com"]
for email in emails:
if email.startswith("andi"):
print("Found Andi")
break
else:
print("Andi not found")
Output:
1 3 5 7
Andi not found
Nested loops
for row in range(1, 4):
line = ""
for col in range(1, 4):
line += f"{row * col:4}"
print(line)
Output:
1 2 3
2 4 6
3 6 9
Common mistakes
- Infinite while loops: forgetting to update the variable in the condition. Press
Ctrl+Cto stop a runaway program. - Off-by-one with range:
range(10)stops at 9, not 10. - Using a chain of separate
ifs when you meantelif: every matchingifwill run. - Modifying a list while looping over it skips items. Loop over a copy (
for x in items[:]) or build a new list. - Writing
for i in range(len(items))when you only need the items. Iterate directly or useenumerate().
Exercise: FizzBuzz
Print the numbers 1 to 15. For multiples of 3 print Fizz, for multiples of 5 print Buzz, and for multiples of both print FizzBuzz. Try it yourself before reading the solution.
for n in range(1, 16):
if n % 15 == 0:
print("FizzBuzz")
elif n % 3 == 0:
print("Fizz")
elif n % 5 == 0:
print("Buzz")
else:
print(n)
Output:
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
Why must the % 15 check come first? Because elif stops at the first match, so 15 would otherwise print just Fizz.
Summary
if/elif/elsechoose one branch;matchis great for many fixed values.foriterates over iterables; combine it withrange(),enumerate(), andzip().whilerepeats until a condition becomes false; usebreak,continue, and loopelseto control the flow.
In Part 4 we will organise code into reusable functions, including *args, **kwargs, scope, and lambdas.
Related articles
PostgreSQL Zero to Advanced #1: Introduction & Setup
Start the series by understanding what a relational database is, installing PostgreSQL locally, and getting comfortable with psql commands like \l, \c and \dt.
PHP Zero to Advanced #1: Introduction & Setup
Start your PHP journey: what PHP is, how to install PHP 8.2+, run the built-in development server, and write your very first script with echo.
Ruby on Rails Zero to Advanced #1: Ruby Basics
Start the Rails journey with the language underneath it: irb, variables, strings, puts vs p, and symbols explained with runnable examples.