Registry Synced

Week 4: Iterations & Ranges

4231 words
21 min read
2026-09-12

Reading compass

Now · TL;DR

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:
  • for loops
  • range()
  • repeated execution
  • loop variables
  • accumulation
  • counting
  • summation
  • products
  • running state
  • tracing loops
  • off-by-one errors
  • nested reasoning with conditionals inside loops
Core model:
initialize state→repeat→update state→finish\boxed{ \text{initialize state} \rightarrow \text{repeat} \rightarrow \text{update state} \rightarrow \text{finish} }

1. Why loops are needed

Suppose you want to print:
text
Hello
five times.
Without iteration:
python
print("Hello")
print("Hello")
print("Hello")
print("Hello")
print("Hello")
This works, but it does not scale.
With a loop:
python
for i in range(5):
    print("Hello")
The repeated structure is expressed once.

2. Iteration

Iteration means repeated execution of a block of instructions.
Conceptually:
text
repeat:
    do something
In Python, one major mechanism is:
python
for ...

3. Basic for loop

python
for i in range(5):
    print(i)
Output:
text
0
1
2
3
4
The body executes once for each value produced by range(5).

4. Loop variable

In:
python
for i in range(5):
i is the loop variable.
Across iterations, it takes values:
0,1,2,3,4.0,1,2,3,4.

5. range(n)

python
range(n)
produces integer values conceptually:
0,1,2,…,n−1.0,1,2,\dots,n-1.
So the number of values is:
n\boxed{n}
for positive integer nn.

6. Crucial endpoint rule

python
range(5)
does not include 5.
It gives:
text
0, 1, 2, 3, 4
This exclusive upper bound is one of the most common sources of mistakes.

7. range(start, stop)

Example:
python
for i in range(2, 6):
    print(i)
Output:
text
2
3
4
5
General idea:
start, start+1,…, stop−1.start,\ start+1,\dots,\ stop-1.

8. Start is included, stop is excluded

For:
python
range(3, 8)
values:
3,4,5,6,7.3,4,5,6,7.
So:
3≤i<8\boxed{ 3\leq i<8 }

9. range(start, stop, step)

Third argument controls step size.
python
range(2, 10, 2)
produces:
text
2, 4, 6, 8

10. Example with step 3

python
for i in range(1, 10, 3):
    print(i)
Output:
text
1
4
7
Next would be 10, but the stop value is excluded.

11. Negative step

Python can count downward.
python
for i in range(5, 0, -1):
    print(i)
Output:
text
5
4
3
2
1

12. Why range(5, 0, -1) stops at 1

The stop value:
text
0
is excluded.
So descending values satisfy:
i>0.i>0.

13. Countdown including zero

Use:
python
range(5, -1, -1)
which gives:
text
5
4
3
2
1
0

14. Loop body indentation

python
for 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:
python
for i in range(3):
    print(i)
Trace:
IterationiOutput
100
211
322
Then loop ends.

16. Loop variable changes automatically

You normally do not need:
python
i = i + 1
inside:
python
for i in range(...)
The for loop itself assigns the next value from the range.

17. Repeated arithmetic

Example:
python
for i in range(1, 6):
    print(i * i)
Outputs:
1,4,9,16,25.1,4,9,16,25.
The expression is recalculated for each i.

18. Printing 1 through 10

Use:
python
for i in range(1, 11):
    print(i)
Not:
python
range(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:
1,…,101,\dots,10
Wrong:
python
range(1, 10)
Correct:
python
range(1, 11)

20. Count number of iterations

For:
python
range(a, b)
with step 1 and b>ab>a, number of values is:
b−a.b-a.
Example:
python
range(3, 8)
has:
8−3=58-3=5
values.

21. Accumulator pattern

One of the most important loop patterns:
python
total = 0

for ...:
    total = total + value
total accumulates information across iterations.

22. Sum 1 through 5

python
total = 0

for i in range(1, 6):
    total = total + i

print(total)
Trace:
0→1→3→6→10→15.0 \to1 \to3 \to6 \to10 \to15.
Final:
15\boxed{15}

23. Trace table

itotal beforetotal after
101
213
336
4610
51015

24. Why initialize sum to zero

For addition:
x+0=x.x+0=x.
So zero is the additive identity.
Starting:
python
total = 0
does not distort the sum.

25. Product accumulator

To multiply values:
python
product = 1

for i in range(1, 5):
    product = product * i
Final:
1⋅1⋅2⋅3⋅4=24.1\cdot1\cdot2\cdot3\cdot4=24.

26. Why product starts at 1

Because:
x⋅1=x.x\cdot1=x.
Starting at 0 would make every product remain:
0.0.

27. Factorial

For positive integer nn:
n!=1⋅2⋯n.n!=1\cdot2\cdots n.
Python:
python
n = int(input())

fact = 1

for i in range(1, n + 1):
    fact = fact * i

print(fact)

28. Example factorial

For:
n=5,n=5,
state:
1→1→2→6→24→120.1 \to1 \to2 \to6 \to24 \to120.
Final:
5!=120\boxed{5!=120}

29. Counter pattern

A counter usually starts at:
python
count = 0
and increases when some event occurs:
python
if condition:
    count = count + 1

30. Count even numbers

python
count = 0

for i in range(1, 11):
    if i % 2 == 0:
        count = count + 1

print(count)
Even values:
2,4,6,8,10.2,4,6,8,10.
So:
count=5\boxed{count=5}

31. Condition inside loop

This structure:
python
for 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:
python
for i in range(1, 11):
    if i % 3 == 0:
        print(i)
Outputs:
text
3
6
9
The loop generates candidates; the if filters them.

33. Sum only selected values

python
total = 0

for i in range(1, 11):
    if i % 2 == 0:
        total = total + i

print(total)
This computes:
2+4+6+8+10=30.2+4+6+8+10=30.

34. Running total

A variable like:
python
total
changes over time.
That is a running total.
At iteration kk, it stores the sum of all relevant values processed so far.

35. Loop invariant intuition

For:
python
total = 0

for i in range(1, n + 1):
    total += i
after processing integer ii, total equals:
1+2+⋯+i.1+2+\cdots+i.
That stable meaning across iterations is an invariant-like way to reason about the loop.

36. Shorthand assignment

Python permits:
python
total += i
instead of:
python
total = total + i
Likewise:
python
count += 1
product *= i

37. For learning, expand mentally

When tracing:
python
x += 3
read it as:
python
x = x + 3
That makes state updates clearer.

38. Sum of squares

Goal:
12+22+⋯+n2.1^2+2^2+\cdots+n^2.
python
total = 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:
python
count = 0

for i in range(1, 101):
    if i % 7 == 0:
        count += 1

print(count)

40. Generate multiples directly

Instead of filtering every number:
python
for i in range(7, 101, 7):
    print(i)
This directly generates:
7,14,21,…,98.7,14,21,\dots,98.
Sometimes the range itself can encode the pattern.

41. Looping a fixed number of times

If you only care about repetition count:
python
for i in range(5):
    print("Hello")
Here i may not be logically important.
Conventionally, Python programmers sometimes use:
python
for _ 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:
python
total = 0

for _ in range(5):
    x = int(input())
    total += x

print(total)
The program reads exactly five inputs.

43. Count positive inputs

python
count = 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

python
total = 0

for _ in range(5):
    x = float(input())
    total += x

average = total / 5

print(average)

45. Generalize to n values

python
n = int(input())

total = 0

for _ in range(n):
    x = float(input())
    total += x

average = total / n

print(average)
This assumes:
n>0.n>0.

46. Maximum over repeated input

Suppose read nn numbers.
One robust strategy:
python
n = 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:
python
maximum = 0
then result incorrectly remains 0 even though 0 was never in the data.
Initialize from actual data when possible.

48. Minimum pattern

python
minimum = 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:
python
total = 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:
python
total = 0
count = 0

for _ in range(n):
    x = float(input())

    if x > 0:
        total += x
        count += 1
Then if:
python
count > 0
we can compute:
python
average = total / count

51. Why count matters

If only selected values contribute, dividing by total number of inputs is wrong.
Example data:
text
5, -2, 7
Positive sum:
12.12.
Positive count:
2.2.
Average:
6.6.
Not:
12/3=4.12/3=4.

52. Arithmetic progression via range

python
range(5, 21, 5)
generates:
5,10,15,20.5,10,15,20.
So range() can represent arithmetic progressions.

53. range and inequalities

For positive step:
python
range(a, b)
roughly corresponds to:
a≤i<b.a\leq i<b.
For step:
python
s>0,
values are:
a, a+s, a+2s,…a,\ a+s,\ a+2s,\dots
while remaining below bb.

54. Negative-step inequality

For:
python
range(10, 2, -2)
values:
10,8,6,4.10,8,6,4.
They continue while:
i>2.i>2.
Stop value still excluded.

55. Empty range

Example:
python
range(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

python
range(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:
python
x = 10

for i in range(0):
    x = x + 1

print(x)
Loop runs zero times.
Output:
10\boxed{10}

58. State after loop

After:
python
for 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:
python
for i in range(5):
    pass
after normal completion, i is typically:
4.4.
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:
python
break
to terminate the nearest loop immediately.
Example:
python
for i in range(10):
    if i == 5:
        break
    print(i)
Output:
text
0
1
2
3
4

61. break trace

At:
i=5,i=5,
condition:
python
i == 5
is true.
break exits the loop before:
python
print(i)
for that iteration.

62. Search pattern with break

Suppose:
python
found = 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:
python
continue
skips the rest of the current iteration and moves to the next one.
Example:
python
for i in range(5):
    if i == 2:
        continue
    print(i)
Output:
text
0
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

python
for i in range(1, 6):
    if i % 2 == 0:
        continue

    print(i)
Output:
text
1
3
5
Even values skip the print.

66. Loop else — supporting Python feature

Python permits an else attached to a loop.
Example:
python
for 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

python
n = 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:
n>1,n>1,
a basic algorithm checks whether any integer:
2≤d<n2\leq d<n
divides nn exactly.
If one does:
text
not prime
If none does:
text
prime
This is a classic loop problem.

69. Basic prime code

python
n = 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

python
is_prime
is a flag.
A flag stores whether some event/condition has occurred.
Other examples:
python
found
valid
seen_negative

71. Flag pattern

python
found = 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:
python
n = 1234

for _ in range(4):
    digit = n % 10
    print(digit)
    n = n // 10
Outputs digits from right to left:
text
4
3
2
1

73. Why % 10

For positive integer:
n mod 10n\bmod10
gives the final decimal digit.
Example:
1234 mod 10=4.1234\bmod10=4.

74. Why // 10

1234//10=123.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:
python
digit = n % 10
total += digit
n = n // 10
This is another accumulator pattern.

76. Pattern printing intuition

Loops can generate repeated output structures.
Example:
python
for 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

python
n = int(input())

for i in range(1, 11):
    print(n * i)
For:
n=7,n=7,
outputs:
7,14,21,…,70.7,14,21,\dots,70.

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:
text
generate
→ process
→ output
→ next

Common mistake: accumulator inside loop
Wrong:
python
for 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

python
total = 0

for i in range(1, 6):
    total += i
Initialization happens once before repetition.

Common mistake: count reset
Wrong:
python
for i in range(10):
    count = 0

    if condition:
        count += 1
The previous count is destroyed on every iteration.

Common mistake: wrong range endpoint
Want:
1,2,3,4,5.1,2,3,4,5.
Wrong:
python
range(1, 5)
Correct:
python
range(1, 6)

Common mistake: wrong negative range
Want:
text
5 4 3 2 1
Wrong:
python
range(5, 1)
because default step is positive.
Correct:
python
range(5, 0, -1)

Common mistake: zero step
python
range(1, 10, 0)
is invalid.
A step cannot be zero because the sequence would never progress.

Common mistake: manually modify
for variable
Example:
python
for 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 loop
python
if x < 10:
    x += 1
runs at most once.
python
for ...
repeats according to an iterable/range.
Selection and iteration are different control structures.

Common mistake: count loop iterations incorrectly
python
for i in range(2, 8):
runs for:
2,3,4,5,6,72,3,4,5,6,7
which is:
6\boxed{6}
iterations.
Not 8.

Common mistake: change state before using old value
Example:
python
total = 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:
python
for ...:
    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:
python
for ...:
    total += x

average = total / n

Common mistake: divide by zero count
For filtered average:
python
average = total / count
only valid when:
count>0.count>0.
Always consider the possibility of zero matching elements.

Common mistake:
break exits all loops
break 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 iteration
No.
continue skips to the next iteration.
It does not restart the same value.

94. Manual loop-tracing workflow

For a loop question:
  1. Write the values produced by range().
  2. Write initial state before the loop.
  3. Process one iteration at a time.
  4. Update variables immediately.
  5. Record output in order.
  6. If break, stop immediately.
  7. If continue, skip remaining body for that iteration.
  8. After final iteration, continue with code after the loop.

95. Trace table template

Program:
python
s = 0

for i in range(1, 5):
    s = s + 2 * i
Use:
i2*is befores after
1202
2426
36612
481220
Final:
s=20\boxed{s=20}

96. Slightly harder trace

python
x = 1

for i in range(1, 5):
    if i % 2 == 0:
        x = x * 2
    else:
        x = x + 3

print(x)
Trace:

i = 1

odd:
x=1+3=4x=1+3=4

i = 2

even:
x=4⋅2=8x=4\cdot2=8

i = 3

odd:
x=8+3=11x=8+3=11

i = 4

even:
x=11⋅2=22x=11\cdot2=22
Output:
22\boxed{22}

97. Loop as repeated state transformation

A loop can be viewed mathematically as repeatedly transforming state:
S0→S1→S2→⋯→Sn.S_0\to S_1\to S_2\to\cdots\to S_n.
For a running sum:
Sk+1=Sk+xk+1.S_{k+1}=S_k+x_{k+1}.
This viewpoint is useful for understanding almost every iterative algorithm.

98. Efficiency intuition

Suppose:
python
for i in range(n):
    ...
The body runs about:
nn
times.
So the amount of repeated work grows with nn.
This later leads naturally to algorithmic complexity ideas.

99. Week 3 → Week 4 transition

Week 3:
text
if condition:
    execute branch
Week 4:
text
for each value:
    execute block
Combined:
python
for i in range(...):
    if condition:
        ...
This is already enough to solve a large class of programming problems.

100. Compact range() cheat sheet

python
range(5)
## 0,1,2,3,4
python
range(2, 6)
## 2,3,4,5
python
range(2, 10, 2)
## 2,4,6,8
python
range(5, 0, -1)
## 5,4,3,2,1
Core rule:
start included, stop excluded\boxed{ \text{start included, stop excluded} }

101. Core loop patterns

Repetition

python
for _ in range(n):
    action

Sum

python
total = 0
for ...:
    total += value

Count

python
count = 0
for ...:
    if condition:
        count += 1

Product

python
product = 1
for ...:
    product *= value

Maximum

python
maximum = first_value
for ...:
    if value > maximum:
        maximum = value
python
found = 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:
  1. Explain iteration.
  2. Write and trace for loops.
  3. Understand the loop variable.
  4. Use range(stop).
  5. Use range(start, stop).
  6. Use range(start, stop, step).
  7. Handle positive and negative steps.
  8. Remember that the stop value is excluded.
  9. Detect off-by-one errors.
  10. Count loop iterations.
  11. Build running sums.
  12. Build counters.
  13. Build running products.
  14. Compute factorials.
  15. Combine if with for.
  16. Filter values during iteration.
  17. Read repeated inputs.
  18. Find running max/min.
  19. Use multiple accumulators.
  20. Understand flags.
  21. Use break.
  22. Use continue.
  23. Trace loop state line-by-line.
  24. Avoid resetting accumulators inside loops.
  25. 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 while loop with condition count < 5 execute if count starts 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
Document outline

Keep your place and jump directly to a heading.

Table of contents

No note selected

Open a chapter to see its outline, backlinks, and sources here.