Week 4: Iterations & Ranges
4231 words
21 min read
2026-09-12T00:00:00.000Z
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
While loops, for loops with range(start, stop, step), loop accumulators, termination conditions, and infinite loop traps. # Programming in Python — Week 4: Iterations & Ranges The official IITM syllabus lists **Week 4: Iterations and Ranges**.

Programming in Python — Week 4: Iterations & Ranges
The official IITM syllabus lists Week 4: Iterations and Ranges.
This is the point where Python moves from one-time decisions to repeated computation.
TL;DR
Conditionals answer:
Should this block run?
Loops answer:
How many times should this block run?
The main Week 4 ideas are:
forloopsrange()- repeated execution
- loop variables
- accumulation
- counting
- summation
- products
- running state
- tracing loops
- off-by-one errors
- nested reasoning with conditionals inside loops
Core model:
1. Why loops are needed
Suppose you want to print:
textHello
five times.
Without iteration:
pythonprint("Hello") print("Hello") print("Hello") print("Hello") print("Hello")
This works, but it does not scale.
With a loop:
pythonfor i in range(5): print("Hello")
The repeated structure is expressed once.
2. Iteration
Iteration means repeated execution of a block of instructions.
Conceptually:
textrepeat: do something
In Python, one major mechanism is:
pythonfor ...
3. Basic for loop
pythonfor i in range(5): print(i)
Output:
text0 1 2 3 4
The body executes once for each value produced by
range(5).4. Loop variable
In:
pythonfor i in range(5):
i is the loop variable.Across iterations, it takes values:
5. range(n)
pythonrange(n)
produces integer values conceptually:
So the number of values is:
for positive integer n.
6. Crucial endpoint rule
pythonrange(5)
does not include 5.
It gives:
text0, 1, 2, 3, 4
This exclusive upper bound is one of the most common sources of mistakes.
7. range(start, stop)
Example:
pythonfor i in range(2, 6): print(i)
Output:
text2 3 4 5
General idea:
8. Start is included, stop is excluded
For:
pythonrange(3, 8)
values:
So:
9. range(start, stop, step)
Third argument controls step size.
pythonrange(2, 10, 2)
produces:
text2, 4, 6, 8
10. Example with step 3
pythonfor i in range(1, 10, 3): print(i)
Output:
text1 4 7
Next would be 10, but the stop value is excluded.
11. Negative step
Python can count downward.
pythonfor i in range(5, 0, -1): print(i)
Output:
text5 4 3 2 1
12. Why range(5, 0, -1) stops at 1
The stop value:
text0
is excluded.
So descending values satisfy:
13. Countdown including zero
Use:
pythonrange(5, -1, -1)
which gives:
text5 4 3 2 1 0
14. Loop body indentation
pythonfor i in range(3): print(i) print("inside") print("outside")
The first two statements repeat.
The final statement executes once after the loop.
15. Trace loop execution
Program:
pythonfor i in range(3): print(i)
Trace:
| Iteration | i | Output |
|---|---|---|
| 1 | 0 | 0 |
| 2 | 1 | 1 |
| 3 | 2 | 2 |
Then loop ends.
16. Loop variable changes automatically
You normally do not need:
pythoni = i + 1
inside:
pythonfor i in range(...)
The
for loop itself assigns the next value from the range.17. Repeated arithmetic
Example:
pythonfor i in range(1, 6): print(i * i)
Outputs:
The expression is recalculated for each
i.18. Printing 1 through 10
Use:
pythonfor i in range(1, 11): print(i)
Not:
pythonrange(1, 10)
because 10 would be excluded.
19. Off-by-one errors
An off-by-one error occurs when a loop runs one too many or one too few times.
Example intended:
Wrong:
pythonrange(1, 10)
Correct:
pythonrange(1, 11)
20. Count number of iterations
For:
pythonrange(a, b)
with step 1 and b>a, number of values is:
Example:
pythonrange(3, 8)
has:
values.
21. Accumulator pattern
One of the most important loop patterns:
pythontotal = 0 for ...: total = total + value
total accumulates information across iterations.22. Sum 1 through 5
pythontotal = 0 for i in range(1, 6): total = total + i print(total)
Trace:
Final:
23. Trace table
i | total before | total after |
|---|---|---|
| 1 | 0 | 1 |
| 2 | 1 | 3 |
| 3 | 3 | 6 |
| 4 | 6 | 10 |
| 5 | 10 | 15 |
24. Why initialize sum to zero
For addition:
So zero is the additive identity.
Starting:
pythontotal = 0
does not distort the sum.
25. Product accumulator
To multiply values:
pythonproduct = 1 for i in range(1, 5): product = product * i
Final:
26. Why product starts at 1
Because:
Starting at 0 would make every product remain:
27. Factorial
For positive integer n:
Python:
pythonn = int(input()) fact = 1 for i in range(1, n + 1): fact = fact * i print(fact)
28. Example factorial
For:
state:
Final:
29. Counter pattern
A counter usually starts at:
pythoncount = 0
and increases when some event occurs:
pythonif condition: count = count + 1
30. Count even numbers
pythoncount = 0 for i in range(1, 11): if i % 2 == 0: count = count + 1 print(count)
Even values:
So:
31. Condition inside loop
This structure:
pythonfor i in range(...): if condition: action
means:
repeat the test for every iteration.
This combines Weeks 2–3 conditionals with Week 4 iteration.
32. Filter pattern
Example:
pythonfor i in range(1, 11): if i % 3 == 0: print(i)
Outputs:
text3 6 9
The loop generates candidates; the
if filters them.33. Sum only selected values
pythontotal = 0 for i in range(1, 11): if i % 2 == 0: total = total + i print(total)
This computes:
34. Running total
A variable like:
pythontotal
changes over time.
That is a running total.
At iteration k, it stores the sum of all relevant values processed so far.
35. Loop invariant intuition
For:
pythontotal = 0 for i in range(1, n + 1): total += i
after processing integer i,
total equals:That stable meaning across iterations is an invariant-like way to reason about the loop.
36. Shorthand assignment
Python permits:
pythontotal += i
instead of:
pythontotal = total + i
Likewise:
pythoncount += 1 product *= i
37. For learning, expand mentally
When tracing:
pythonx += 3
read it as:
pythonx = x + 3
That makes state updates clearer.
38. Sum of squares
Goal:
pythontotal = 0 for i in range(1, n + 1): total += i ** 2 print(total)
39. Count multiples
Count numbers from 1 to 100 divisible by 7:
pythoncount = 0 for i in range(1, 101): if i % 7 == 0: count += 1 print(count)
40. Generate multiples directly
Instead of filtering every number:
pythonfor i in range(7, 101, 7): print(i)
This directly generates:
Sometimes the range itself can encode the pattern.
41. Looping a fixed number of times
If you only care about repetition count:
pythonfor i in range(5): print("Hello")
Here
i may not be logically important.Conventionally, Python programmers sometimes use:
pythonfor _ in range(5): print("Hello")
to indicate the loop variable is intentionally unused.
42. Input repeated several times
Suppose read 5 numbers and sum them:
pythontotal = 0 for _ in range(5): x = int(input()) total += x print(total)
The program reads exactly five inputs.
43. Count positive inputs
pythoncount = 0 for _ in range(5): x = int(input()) if x > 0: count += 1 print(count)
The state
count survives across iterations.44. Average of fixed number of inputs
pythontotal = 0 for _ in range(5): x = float(input()) total += x average = total / 5 print(average)
45. Generalize to n values
pythonn = int(input()) total = 0 for _ in range(n): x = float(input()) total += x average = total / n print(average)
This assumes:
46. Maximum over repeated input
Suppose read n numbers.
One robust strategy:
pythonn = int(input()) maximum = float(input()) for _ in range(n - 1): x = float(input()) if x > maximum: maximum = x print(maximum)
This uses the first value as the initial maximum.
47. Why not initialize maximum to 0?
Suppose all inputs are:
text-5 -3 -10
If:
pythonmaximum = 0
then result incorrectly remains 0 even though 0 was never in the data.
Initialize from actual data when possible.
48. Minimum pattern
pythonminimum = float(input()) for _ in range(n - 1): x = float(input()) if x < minimum: minimum = x
Same logic with reversed comparison.
49. Multiple accumulators
A loop may update several pieces of state.
Example:
pythontotal = 0 count_positive = 0 for _ in range(n): x = int(input()) total += x if x > 0: count_positive += 1
One pass can compute multiple summaries.
50. Sum and count for conditional average
Suppose average of positive values only:
pythontotal = 0 count = 0 for _ in range(n): x = float(input()) if x > 0: total += x count += 1
Then if:
pythoncount > 0
we can compute:
pythonaverage = total / count
51. Why count matters
If only selected values contribute, dividing by total number of inputs is wrong.
Example data:
text5, -2, 7
Positive sum:
Positive count:
Average:
Not:
52. Arithmetic progression via range
pythonrange(5, 21, 5)
generates:
So
range() can represent arithmetic progressions.53. range and inequalities
For positive step:
pythonrange(a, b)
roughly corresponds to:
For step:
pythons>0,
values are:
while remaining below b.
54. Negative-step inequality
For:
pythonrange(10, 2, -2)
values:
They continue while:
Stop value still excluded.
55. Empty range
Example:
pythonrange(5, 2)
with default positive step.
There are no values because you cannot move upward from 5 and reach something below 2.
So loop body executes zero times.
56. Another empty range
pythonrange(2, 5, -1)
is empty because step moves downward while stop lies upward.
The step direction must be compatible with the interval.
57. Zero iterations matter
Program:
pythonx = 10 for i in range(0): x = x + 1 print(x)
Loop runs zero times.
Output:
58. State after loop
After:
pythonfor i in range(5): ...
the loop is over once all range values are consumed.
Anything after the loop executes once.
Do not mentally keep repeating later statements.
59. Final value of loop variable
In ordinary Python:
pythonfor i in range(5): pass
after normal completion,
i is typically:But do not rely on this unless the problem specifically asks about it; the important logical role is the sequence during iteration.
60. break
Python provides:
pythonbreak
to terminate the nearest loop immediately.
Example:
pythonfor i in range(10): if i == 5: break print(i)
Output:
text0 1 2 3 4
61. break trace
At:
condition:
pythoni == 5
is true.
break exits the loop before:pythonprint(i)
for that iteration.
62. Search pattern with break
Suppose:
pythonfound = False for i in range(1, 101): if i * i == target: found = True break
Once the desired item is found, further iterations are unnecessary.
63. continue
Python:
pythoncontinue
skips the rest of the current iteration and moves to the next one.
Example:
pythonfor i in range(5): if i == 2: continue print(i)
Output:
text0 1 3 4
64. continue is not break
continue
Skip current iteration, loop continues.
break
End loop entirely.
This distinction is fundamental.
65. Example with continue
pythonfor i in range(1, 6): if i % 2 == 0: continue print(i)
Output:
text1 3 5
Even values skip the print.
66. Loop else — supporting Python feature
Python permits an
else attached to a loop.Example:
pythonfor i in range(5): if i == target: print("Found") break else: print("Not found")
The
else executes if the loop ends normally without break.This is useful Python knowledge, though it may not be central to the official Week 4 heading.
67. Searching for a divisor
pythonn = int(input()) found_divisor = False for d in range(2, n): if n % d == 0: found_divisor = True break
This tests candidate divisors.
It illustrates repetition + condition + early exit.
68. Prime-number intuition
For integer:
a basic algorithm checks whether any integer:
divides n exactly.
If one does:
textnot prime
If none does:
textprime
This is a classic loop problem.
69. Basic prime code
pythonn = int(input()) is_prime = n > 1 for d in range(2, n): if n % d == 0: is_prime = False break if is_prime: print("Prime") else: print("Not prime")
70. Boolean flag
pythonis_prime
is a flag.
A flag stores whether some event/condition has occurred.
Other examples:
pythonfound valid seen_negative
71. Flag pattern
pythonfound = False for ...: if desired_condition: found = True break if found: ... else: ...
This pattern is very common.
72. Repeated digit-like arithmetic
Loops can repeatedly apply arithmetic transformations.
Example:
pythonn = 1234 for _ in range(4): digit = n % 10 print(digit) n = n // 10
Outputs digits from right to left:
text4 3 2 1
73. Why % 10
For positive integer:
gives the final decimal digit.
Example:
74. Why // 10
1234//10=123.
It removes the final decimal digit for positive integers.
This lets a loop repeatedly process digits.
75. Build sum of digits
For a known number of digits or with a later
while loop, the pattern is:pythondigit = n % 10 total += digit n = n // 10
This is another accumulator pattern.
76. Pattern printing intuition
Loops can generate repeated output structures.
Example:
pythonfor i in range(1, 6): print("*" * i)
Output:
text* ** *** **** *****
The loop controls size.
77. String repetition
Python:
python"*" * 4
produces:
text****
Combining this with a loop generates simple patterns.
78. Multiplication table
pythonn = int(input()) for i in range(1, 11): print(n * i)
For:
outputs:
79. Repetition can generate instead of store
Notice the multiplication table need not first create a list.
Each result can be computed and printed immediately.
This is streaming-style thinking:
textgenerate → process → output → next
Common mistake: accumulator inside loop
Wrong:
pythonfor i in range(1, 6): total = 0 total += i
total resets every iteration.After each iteration it contains only the current
i.81. Correct accumulator placement
pythontotal = 0 for i in range(1, 6): total += i
Initialization happens once before repetition.
Common mistake: count reset
Wrong:
pythonfor i in range(10): count = 0 if condition: count += 1
The previous count is destroyed on every iteration.
Common mistake: wrong range endpoint
Want:
Wrong:
pythonrange(1, 5)
Correct:
pythonrange(1, 6)
Common mistake: wrong negative range
Want:
text5 4 3 2 1
Wrong:
pythonrange(5, 1)
because default step is positive.
Correct:
pythonrange(5, 0, -1)
Common mistake: zero step
pythonrange(1, 10, 0)
is invalid.
A step cannot be zero because the sequence would never progress.
Common mistake: manually modify
for variableExample:
pythonfor i in range(5): i = i + 10
This changes
i during the current iteration, but the next iteration receives the next value from the range.Do not treat Python
for as a manually controlled counter loop.Common mistake:
if confused with looppythonif x < 10: x += 1
runs at most once.
pythonfor ...
repeats according to an iterable/range.
Selection and iteration are different control structures.
Common mistake: count loop iterations incorrectly
pythonfor i in range(2, 8):
runs for:
which is:
iterations.
Not 8.
Common mistake: change state before using old value
Example:
pythontotal = 0 for i in range(3): total = total + i
Trace each assignment sequentially.
Do not calculate all updates as though
total remained 0.Common mistake: divide before loop finishes
Suppose computing average.
Wrong structure:
pythonfor ...: total += x average = total / n
This repeatedly computes partial averages.
It may still end with the correct final value in some cases, but the intended algorithm is clearer as:
pythonfor ...: total += x average = total / n
Common mistake: divide by zero count
For filtered average:
pythonaverage = total / count
only valid when:
Always consider the possibility of zero matching elements.
Common mistake:
break exits all loopsbreak exits only the nearest enclosing loop.This becomes especially important once nested loops appear.
For Week 4 single loops, just remember it terminates the current loop.
Common mistake:
continue repeats same iterationNo.
continue skips to the next iteration.It does not restart the same value.
94. Manual loop-tracing workflow
For a loop question:
- Write the values produced by
range(). - Write initial state before the loop.
- Process one iteration at a time.
- Update variables immediately.
- Record output in order.
- If
break, stop immediately. - If
continue, skip remaining body for that iteration. - After final iteration, continue with code after the loop.
95. Trace table template
Program:
pythons = 0 for i in range(1, 5): s = s + 2 * i
Use:
i | 2*i | s before | s after |
|---|---|---|---|
| 1 | 2 | 0 | 2 |
| 2 | 4 | 2 | 6 |
| 3 | 6 | 6 | 12 |
| 4 | 8 | 12 | 20 |
Final:
96. Slightly harder trace
pythonx = 1 for i in range(1, 5): if i % 2 == 0: x = x * 2 else: x = x + 3 print(x)
Trace:
i = 1
odd:
i = 2
even:
i = 3
odd:
i = 4
even:
Output:
97. Loop as repeated state transformation
A loop can be viewed mathematically as repeatedly transforming state:
For a running sum:
This viewpoint is useful for understanding almost every iterative algorithm.
98. Efficiency intuition
Suppose:
pythonfor i in range(n): ...
The body runs about:
times.
So the amount of repeated work grows with n.
This later leads naturally to algorithmic complexity ideas.
99. Week 3 → Week 4 transition
Week 3:
textif condition: execute branch
Week 4:
textfor each value: execute block
Combined:
pythonfor i in range(...): if condition: ...
This is already enough to solve a large class of programming problems.
100. Compact range() cheat sheet
pythonrange(5) ## 0,1,2,3,4
pythonrange(2, 6) ## 2,3,4,5
pythonrange(2, 10, 2) ## 2,4,6,8
pythonrange(5, 0, -1) ## 5,4,3,2,1
Core rule:
101. Core loop patterns
Repetition
pythonfor _ in range(n): action
Sum
pythontotal = 0 for ...: total += value
Count
pythoncount = 0 for ...: if condition: count += 1
Product
pythonproduct = 1 for ...: product *= value
Maximum
pythonmaximum = first_value for ...: if value > maximum: maximum = value
Search
pythonfound = False for ...: if condition: found = True break
102. What you should actually master
By the end of Python Week 4, you should be able to:
- Explain iteration.
- Write and trace
forloops. - Understand the loop variable.
- Use
range(stop). - Use
range(start, stop). - Use
range(start, stop, step). - Handle positive and negative steps.
- Remember that the stop value is excluded.
- Detect off-by-one errors.
- Count loop iterations.
- Build running sums.
- Build counters.
- Build running products.
- Compute factorials.
- Combine
ifwithfor. - Filter values during iteration.
- Read repeated inputs.
- Find running max/min.
- Use multiple accumulators.
- Understand flags.
- Use
break. - Use
continue. - Trace loop state line-by-line.
- Avoid resetting accumulators inside loops.
- Recognize zero-iteration cases.
If these are comfortable, Programming in Python Week 4 is under control.
Quick Recall & Flashcards
Test your active recall before proceeding to practice problems. Format:
Question :: Answer.- Week 4 Diagnostic: What is the sequence of integers generated by
list(range(2, 10, 3))? :: Answer: A — range(start, stop, step) starts at 2, steps by 3, and stops before 10: 2, 5, 8. - Week 4 Diagnostic: How many times will a
whileloop with conditioncount < 5execute ifcountstarts at 0 and increments by 1 each iteration? :: Answer: 5 — Iterations for count = 0, 1, 2, 3, 4 -> 5 times.
Practice & Self-Check
Attempt these diagnostic questions to verify your operational understanding.
1
Question 1
What is the sequence of integers generated by
list(range(2, 10, 3))?MCQ
3 Unit Assessment
A. [2, 5, 8]
B. [2, 5, 8, 10]
C. [3, 6, 9]
D. [2, 3, 4, 5, 6, 7, 8, 9]
2
Question 2
How many times will a
while loop with condition count < 5 execute if count starts at 0 and increments by 1 each iteration?NAT
3 Unit Assessment