Quiz 2

Programming in Python · Week 4 — Iterations & ranges

1145 words
6 min read
2026-08-16T00:00:00.000Z
Python Week 1: the first filter for runtime behavior
Visual companion
Python
Type and operator map

Python Week 1: the first filter for runtime behavior

View
Revision summary

What this note is really saying

Short form

for, while, range(), accumulation — concepts, pattern families, and traps for Quiz 2 week 4. # Week 4 — iterations & ranges > **Quiz 2 scope:** Weeks 1–8 per IITM May 2026 foundation courses.

Week 4 — iterations & ranges

Quiz 2 scope: Weeks 1–8 per IITM May 2026 foundation courses. Source baseline: IITM BS admissions important-dates calendar · May 2026 cycle. Times on assessments are operational conventions — verify hall ticket.
Part of the Quiz 2 prep system%20%C2%B7%20%5BWeeks%201%E2%80%938%20index%5D(.%2Fmay-2026-python-quiz-2-weeks-1-8-prep) · Pattern atlas · Formula chains.

Week map

Loop choice → range endpoints → accumulator → termination

Classify → Represent → Execute → Trap-check

  • Recognize: Ask: How many values does range(3, 8) produce?
  • Procedure: range(5) gives 0..4 (five values). range(2,7) gives 2..6. Step defaults to 1; negative step counts down when start > stop.
  • Variations / traps: Watch for: range(1, n) vs range(n) off-by-one.

Formula chain (compressed)

for/while → range(start,stop,step) → accumulator → loop invariant.
  1. for loopfor x in seq: — known iteration count
  2. while loopwhile cond: — stop when condition false
  3. rangerange(n), range(a,b), range(a,b,s) — 0..n-1 or stepped
  4. Accumulatortotal = total + x — sum/count/product patterns
  5. Infinite loop trapcond never becomes false — check update inside while

Deep study

Programming in Python · Week 4 — Iterations and range

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 → i takes each value produced by range → body runs once per value.
  • range(stop) → integers 0, 1, …, stop-1range(4) → 0,1,2,3 (four values).
  • range(start, stop) → from start inclusive to stop exclusive → 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

python
total = 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 until cond false; must ensure progress toward termination.
Mini-while:
python
n = 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 string s.
  • 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 == 0 inside loop).
  • while with compound update; detect infinite loop risk if condition never changes.
  • Nested setup for week 5 preview: outer i, inner j — 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.
python
s = 0
for i in range(1, 11):
    s += i
# s = 55
Example 3 — Count evens.
python
data = [4, 7, 2, 9, 0, 6]
c = 0
for x in data:
    if x % 2 == 0:
        c += 1
# c = 4
Example 4 — while decay.
python
val = 20
steps = 0
while val >= 10:
    val = val - 6
    steps += 1
# val = 8, steps = 2
Example 5 — step range.
python
t = 0
for j in range(0, 15, 3):
    t += j
# j: 0,3,6,9,12 → t = 30

Traps

  • range(1, n) vs range(n) — classic off-by-one.
  • Forgetting accumulator initialization (total = 0 missing).
  • Modifying loop variable expecting to change how many iterations — range already fixed.
  • while True without break path.
  • Using = instead of += in accumulation (total = x resets each time).

Diagnostic (try yourself)

  1. How many numbers does range(5, 15) generate? List them.
  2. What is the final value of sum?
python
sum = 0
for i in range(2, 8):
    sum = sum + i
  1. What is printed?
python
prod = 1
for k in range(1, 5):
    prod = prod * 2
print(prod)
  1. Write a loop that prints integers 10 down to 1 (inclusive) using range with a negative step.
  2. After this loop, what is n?
python
n = 50
while n > 1:
    n = n // 2

ChatGPT prep archive

Archived import for extra depth — complements the notes above, not official IITM material.

Core concepts

  • for loop: iterate over sequence or range(start, stop, step); stop is exclusive.
  • while loop: repeat while condition true; needs progress toward false to avoid infinite loop.
  • Accumulator: variable updated each iteration (total += x).
  • Loop variable takes each value in turn; may be unused with for _ in range(n).

Notation & vocabulary

LoopTypical use
for i in range(n):counted repetition
while cond:repeat until condition fails
range(a,b)integers from a up to but not b

Pattern families

Easy — Count iterations

range(5) gives 0..4 (five values). range(2,7) gives 2..6. Step defaults to 1; negative step counts down when start > stop.

Medium — Accumulator trace

Initialize before loop. Each pass updates from current value. Print after loop if question asks final total—not inside unless printing each step.

Hard — while with guard

Identify condition and what changes each iteration. Check invariant: condition eventually false. Common pattern: read until sentinel value.
Drill these on the pattern atlas — filter to week 4.

Traps

  • range(1, n) vs range(n) off-by-one.
  • Forgetting to initialize accumulator.
  • Modifying loop variable expecting to change range length.
  • while True without break exit path.

Retrieval prompts

  1. How many values does range(3, 8) produce?
  2. Where must an accumulator be initialized?
  3. When prefer for over while?

Practice loop

  1. Read Deep study (if present) or core concepts once.
  2. Recite the formula chain without looking.
  3. Open one easy pattern on the interactive atlas for week 4.
  4. Attempt without solutions; mark studied after an honest try.
  5. Say one trap aloud before closing the tab.
Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.