For three days you learned tools one at a time. Today there are no new keywords. The skill is wiring what you already have together.
if inside a loop — decide on every stepA loop on its own does the same thing every pass. Add a condition inside it, and each pass can react: count only the even ones, stop early, print a different character. That combination is the engine behind almost every program you'll ever write.
# A loop that *reacts* on every step:
for n in range(1, 11):
if n % 2 == 0: # condition INSIDE the loop
print(n, "is even")
For every single pass of the outer loop, the inner loop runs all the way through. Outer counts rows; inner counts columns.
for row in range(3): # outer: 0,1,2
for col in range(3): # inner: 0,1,2
print(row, col)
# 0 0 / 0 1 / 0 2
# 1 0 / 1 1 / 1 2
# 2 0 / 2 1 / 2 2
for row in range(1, 5):
for star in range(row):
print("*", end="")
print() # end the row
*
**
***
****
print("*", end="") keeps the cursor on the same line; a bare print() after the inner loop ends the row. The inner loop count depends on row — that's why it grows.
Put an if inside the loop and the body can behave differently every time — count, filter, or branch on the current value.
count = 0
for n in range(1, 21):
if n % 2 == 0: # decide on THIS number
count = count + 1
print(f"There are {count} even numbers from 1 to 20.")
# → There are 10 even numbers from 1 to 20.
Start with a hopeful guess. Loop looking for evidence against it. The moment you find evidence, you can decide and stop. This is how is_prime works.
def is_prime(n):
if n < 2:
return False # 0, 1, negatives
for d in range(2, n):
if n % d == 0:
return False # found a divisor — done
return True # nothing divided it
return False — no point checking the rest. The final return True only runs if the loop finished clean.
Loop over numbers, ask a question about each (the flag pattern, hidden in is_prime), and print the ones that pass.
for n in range(2, 11):
if is_prime(n): # condition inside the loop
print(n)
# → 2 / 3 / 5 / 7
is_prime), then call it inside a loop. Don't copy-paste the logic.
if must sit inside the outer loop, not beside it.print() after the inner loop — your triangle prints on one long line.end="" — every star jumps to a new line.n < 2 check in is_prime — then 1 and 0 wrongly look prime.return True inside the loop — it fires on the first non-divisor and never checks the rest.
Print a left-aligned right triangle of *. Row 1 has one star, row height has height stars. A nested loop.
Return True/False. Handle n < 2, then loop the divisors — the flag pattern.
students/<your-username>/D09_patterns_and_primes.py. Full brief in lab/module_1_foundations/D09_patterns_and_primes/problem.md. PR before 12:00.