Neural Sync Active
python-week4
Registry Synced
python-week4
608 words
3 min read
Reading compass
Now · Week map
Loops repeat work. Week 4 focuses on counted repetition (
for + range) and accumulators — sums, counts, products.Week map
Why loop →
for over sequence → range start/stop/step → accumulator pattern → while guard → off-by-one discipline.Loop notation
for i in range(n):→ counted loop →itakes each value produced byrange→ body runs once per value.range(stop)→ integers0, 1, …, stop-1→range(4)→ 0,1,2,3 (four values).range(start, stop)→ fromstartinclusive tostopexclusive →range(2,6)→ 2,3,4,5.range(start, stop, step)→ step size →range(0,10,2)→ 0,2,4,6,8.
Trap:
stop is never included. range(1,5) has 4 values, not 5.Accumulator
pythontotal = 0 # neutral for sum for k in range(5): total = total + k # total = 0+1+2+3+4 = 10
Initialize before loop. Update inside loop.
for vs while
for— known iteration count or explicit sequence.while cond:— repeat untilcondfalse; must ensure progress toward termination.
Mini-
while:pythonn = 8 while n > 0: n = n - 3 # n goes 8→5→2→-1, stops; loop ran 3 times
Pattern families
Easy — Count iterations
- How many values does
range(a,b)produce? →max(0, b-a)for step 1. - List indices visited:
range(len(s))for strings. - Final loop variable value after
for(last assigned value remains).
Medium — Accumulator trace
- Sum 1..n, sum of squares, count positives in fixed list.
- Product accumulator starts at 1, not 0.
- Print once after loop vs each iteration.
Hard — Combined condition in loop
- Sum only entries meeting predicate (
if x % 2 == 0inside loop). whilewith compound update; detect infinite loop risk if condition never changes.- Nested setup for week 5 preview: outer
i, innerj— count pairs briefly.
Worked mini-examples
Example 1 — range count.
range(3, 11) → 3,4,5,6,7,8,9,10 → eight iterations.Example 2 — Sum 1 to 10.
pythons = 0 for i in range(1, 11): s += i # s = 55
Example 3 — Count evens.
pythondata = [4, 7, 2, 9, 0, 6] c = 0 for x in data: if x % 2 == 0: c += 1 # c = 4
Example 4 — while decay.
pythonval = 20 steps = 0 while val >= 10: val = val - 6 steps += 1 # val = 8, steps = 2
Example 5 — step range.
pythont = 0 for j in range(0, 15, 3): t += j # j: 0,3,6,9,12 → t = 30
Traps
range(1, n)vsrange(n)— classic off-by-one.- Forgetting accumulator initialization (
total = 0missing). - Modifying loop variable expecting to change how many iterations —
rangealready fixed. while Truewithoutbreakpath.- Using
=instead of+=in accumulation (total = xresets each time).
Diagnostic (try yourself)
-
How many numbers does
range(5, 15)generate? List them. -
What is the final value of
sum?
pythonsum = 0 for i in range(2, 8): sum = sum + i
- What is printed?
pythonprod = 1 for k in range(1, 5): prod = prod * 2 print(prod)
-
Write a loop that prints integers 10 down to 1 (inclusive) using
rangewith a negative step. -
After this loop, what is
n?
pythonn = 50 while n > 1: n = n // 2