Week 5: Loop Controls & Patterns

4565 words
23 min read
2026-09-12T00: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

Break, continue, loop else clause, nested iterations, 2D pattern generation, and prime testing algorithms. # Programming in Python — Week 5: Loop Controls & Patterns The official IITM syllabus lists **Week 5: Iterations and Ranges (Continued)**.

Visual strip

Relevant recall pieces for this note

Open gallery

Programming in Python — Week 5: Loop Controls & Patterns

The official IITM syllabus lists Week 5: Iterations and Ranges (Continued). It does not provide a finer breakdown in the syllabus file, so the detailed material below is a standard continuation of iteration/range problem-solving, rather than a claim about the exact lecture sequence.

TL;DR

Week 4 established:
python
for i in range(...):
    ...
Week 5 pushes iteration further:
  • while loops
  • condition-controlled repetition
  • nested loops
  • loop tracing
  • break and continue
  • counters and accumulators in harder problems
  • digit-processing algorithms
  • repeated transformation
  • searching
  • patterns
  • choosing for vs while
  • preventing infinite loops
The central distinction is:
for: iterate over a known sequence\boxed{ \texttt{for}: \text{ iterate over a known sequence} }
versus:
while: repeat while a condition remains true\boxed{ \texttt{while}: \text{ repeat while a condition remains true} }

1. Two major repetition styles

Count/sequence-controlled

python
for i in range(10):
    ...
You know what values drive the repetitions.

Condition-controlled

python
while condition:
    ...
You continue until some changing condition becomes false.

2. Basic while

Syntax:
python
while condition:
    statements
Python:
  1. evaluates condition
  2. if true, executes body
  3. returns to condition
  4. repeats
  5. stops when condition becomes false

3. Example

python
x = 1

while x <= 5:
    print(x)
    x = x + 1
Output:
text
1
2
3
4
5

4. Trace the state

Iterationx before testTest x <= 5Printedx after update
11True12
22True23
33True34
44True45
55True56
stop6False——
Final:
x=6.x=6.

5. while has three essential pieces

A typical counter-based while needs:

Initialization

python
i = 1

Condition

python
while i <= 5:

Update

python
i += 1
Together:
python
i = 1

while i <= 5:
    print(i)
    i += 1

6. Missing update → infinite loop

Wrong:
python
i = 1

while i <= 5:
    print(i)
i never changes.
So:
python
i <= 5
remains true forever.
Conceptually:
1→1→1→1→⋯1\to1\to1\to1\to\cdots

7. Infinite loop

An infinite loop is a loop whose termination condition is never reached.
Example:
python
while True:
    print("hello")
This intentionally runs forever unless something such as break terminates it.

8. Progress toward termination

When analysing a while loop, always ask:
What changes each iteration so that the condition eventually becomes false?
Example:
python
x = 100

while x > 0:
    x = x - 10
x decreases toward 0.
Termination is easy to reason about.

9. Wrong update direction

python
x = 1

while x < 10:
    x = x - 1
x becomes:
1,0,−1,−2,…1,0,-1,-2,\dots
It moves away from 10.
So condition remains true forever.

10. for equivalent

This:
python
for i in range(1, 6):
    print(i)
can be expressed:
python
i = 1

while i <= 5:
    print(i)
    i += 1
For a simple fixed numerical progression, for/range is generally cleaner.

11. When while is more natural

Suppose:
Keep reading numbers until the user enters 0.
You do not know beforehand how many inputs will appear.
That naturally fits:
python
x = int(input())

while x != 0:
    print(x)
    x = int(input())

12. Sentinel value

The special value:
text
0
in the previous example acts as a sentinel.
A sentinel marks:
stop processing
Other possible sentinels:
text
-1
"quit"
"end"
depending on the problem.

13. Sentinel is usually not processed

Example:
python
total = 0

x = int(input())

while x != -1:
    total += x
    x = int(input())
Here:
text
-1
terminates input and is not added to the total.

14. Sentinel trace

Inputs:
text
5
8
2
-1
State:
0→5→13→15.0\to5\to13\to15.
At -1:
python
x != -1
is false.
Final:
15\boxed{15}

15. Count unknown number of inputs

python
count = 0
x = int(input())

while x != -1:
    count += 1
    x = int(input())

print(count)
If inputs are:
text
3
9
4
7
-1
then:
count=4.count=4.

16. Sum and count together

python
total = 0
count = 0

x = float(input())

while x != -1:
    total += x
    count += 1
    x = float(input())
Then:
python
if count > 0:
    average = total / count

17. Why the count > 0 check matters

Input could immediately be:
text
-1
Then:
count=0.count=0.
Trying:
python
total / count
would divide by zero.

18. Input-validation loop

while is useful when input must satisfy a condition.
python
x = int(input())

while x < 0:
    x = int(input())
This keeps asking until:
x≥0.x\geq0.

19. Validation example

python
marks = int(input())

while marks < 0 or marks > 100:
    marks = int(input())

print(marks)
Loop invariant after termination:
0≤marks≤100\boxed{ 0\leq marks\leq100 }

20. while True + break

Another common style:
python
while True:
    x = int(input())

    if x == 0:
        break

    print(x)
The loop is structurally infinite, but break provides termination.

21. break

break exits the nearest enclosing loop immediately.
python
while True:
    x = int(input())

    if x < 0:
        break
Once x < 0, execution jumps outside the loop.

22. continue

continue skips the rest of the current iteration.
python
for i in range(1, 6):
    if i == 3:
        continue

    print(i)
Output:
text
1
2
4
5

23. continue in a while loop can be dangerous

Example:
python
i = 0

while i < 5:
    if i == 2:
        continue

    i += 1
When:
i=2,i=2,
continue happens before i += 1.
So i remains 2 forever.
This causes an infinite loop.

24. Safer update reasoning

When using while, ensure every possible path through the loop either:
  • changes state toward termination, or
  • executes break
This is especially important when continue is present.

25. Repeated multiplication

Example:
python
x = 1

while x < 100:
    x = x * 2
Trace:
1→2→4→8→16→32→64→128.1\to2\to4\to8\to16\to32\to64\to128.
Then:
128<100128<100
is false.
Final:
128\boxed{128}

26. Number of iterations can be non-obvious

In:
python
x = 1

while x < 100:
    x *= 2
the number of repetitions is determined by how quickly repeated doubling crosses 100.
Unlike:
python
for i in range(7):
the count is not explicitly written.

27. Digit processing with while

One of the most important numerical loop patterns:
python
digit = n % 10
n = n // 10
For positive integer n:
  • % 10 extracts last digit
  • // 10 removes last digit

28. Example

Start:
n=5382.n=5382.
Then:
5382 mod 10=25382\bmod10=2
and:
5382//10=538.5382//10=538.
Next:
538 mod 10=8.538\bmod10=8.
So digits can be processed right-to-left.

29. Print digits in reverse order

python
n = int(input())

while n > 0:
    digit = n % 10
    print(digit)
    n = n // 10
For:
text
5382
output:
text
2
8
3
5

30. Sum of digits

python
n = int(input())
total = 0

while n > 0:
    digit = n % 10
    total += digit
    n //= 10

print(total)
For:
5382,5382, 5+3+8+2=18.5+3+8+2=18.

31. Trace sum of digits

ndigittotal
538222
538810
53313
5518
0—stop
Final:
18\boxed{18}

32. Count digits

python
n = int(input())
count = 0

while n > 0:
    count += 1
    n //= 10

print(count)
For:
5382,5382,
count:
4.4.

33. Special case n = 0

The previous loop:
python
while n > 0:
executes zero times when:
n=0.n=0.
Yet decimal representation of 0 has one digit.
So some problems need explicit handling:
python
if n == 0:
    count = 1
else:
    ...
Edge cases still matter inside loop algorithms.

34. Reverse a number

Suppose:
n=1234.n=1234.
Goal:
4321.4321.
Algorithm:
python
reverse = 0

while n > 0:
    digit = n % 10
    reverse = reverse * 10 + digit
    n //= 10

35. Reverse trace

Start:
reverse=0.reverse=0.
Extract 4:
0⋅10+4=4.0\cdot10+4=4.
Extract 3:
4⋅10+3=43.4\cdot10+3=43.
Extract 2:
43⋅10+2=432.43\cdot10+2=432.
Extract 1:
432⋅10+1=4321.432\cdot10+1=4321.

36. Palindrome number

A number such as:
12211221
reads the same forward and backward.
Conceptual algorithm:
  1. save original number
  2. compute reverse
  3. compare reverse with original
python
original = n
reverse = 0

while n > 0:
    digit = n % 10
    reverse = reverse * 10 + digit
    n //= 10

if reverse == original:
    print("Palindrome")

37. Why save original?

The digit loop destroys n:
1221→122→12→1→0.1221\to122\to12\to1\to0.
If you need the original afterward, save it before mutation.
This is the same preservation principle seen in earlier algorithms.

38. Nested loops

A loop can appear inside another loop.
python
for i in range(3):
    for j in range(2):
        print(i, j)
The inner loop runs completely for every outer-loop iteration.

39. Trace nested loops

Outer:
i=0.i=0.
Inner:
j=0,1.j=0,1.
Then outer:
i=1i=1
and inner resets:
j=0,1.j=0,1.
Then:
i=2i=2
with:
j=0,1.j=0,1.

40. Output

text
0 0
0 1
1 0
1 1
2 0
2 1
Number of iterations:
3×2=6.3\times2=6.

41. General nested-loop count

python
for i in range(m):
    for j in range(n):
        action
action executes:
mn\boxed{mn}
times.

42. Square nested loop

python
for i in range(n):
    for j in range(n):
        action
executes:
n2n^2
times.
This connects directly to CT nested-iteration reasoning.

43. Triangle pattern

python
for i in range(1, 5):
    for j in range(i):
        print("*", end="")
    print()
Output:
text
*
**
***
****

44. Why inner loop depends on i

For:
i=1i=1
inner loop runs once.
For:
i=2i=2
twice.
For:
i=3i=3
three times.
So total stars:
1+2+3+4=10.1+2+3+4=10.

45. Nested-loop total work

If inner count changes with outer index:
python
for i in range(1, n + 1):
    for j in range(i):
        ...
total executions:
1+2+⋯+n=n(n+1)2.1+2+\cdots+n = \frac{n(n+1)}2.

46. Multiplication table grid

python
for i in range(1, 4):
    for j in range(1, 4):
        print(i * j, end=" ")
    print()
Output:
text
1 2 3
2 4 6
3 6 9
Outer loop controls rows.
Inner loop controls columns.

47. Coordinate-pair generation

python
for i in range(3):
    for j in range(3):
        print(i, j)
visits every ordered pair:
(i,j)∈{0,1,2}2.(i,j)\in\{0,1,2\}^2.
Total:
9.9.

48. Unique unordered pairs

If we need each pair once:
python
for i in range(n):
    for j in range(i + 1, n):
        print(i, j)
This avoids:
  • self-pairs (i,i)(i,i)
  • duplicate reversed pairs

49. Number of unique pairs

Total:
(n−1)+(n−2)+⋯+1(n-1)+(n-2)+\cdots+1
which equals:
n(n−1)2\boxed{ \frac{n(n-1)}2 }
This is the same pair-count idea from Computational Thinking.

50. break in nested loops

Consider:
python
for i in range(3):
    for j in range(3):
        if j == 1:
            break
        print(i, j)
break exits only the inner loop.

51. Output

For each i:
  • j=0 prints
  • j=1 triggers break
So:
text
0 0
1 0
2 0
Outer loop continues.

52. continue in nested loops

python
for i in range(3):
    for j in range(3):
        if i == j:
            continue
        print(i, j)
This skips pairs:
(0,0),(1,1),(2,2).(0,0),(1,1),(2,2).
It processes only distinct-coordinate pairs.

53. Nested conditional filtering

Example:
python
count = 0

for i in range(1, 6):
    for j in range(1, 6):
        if i + j == 6:
            count += 1
Valid ordered pairs:
(1,5),(2,4),(3,3),(4,2),(5,1).(1,5),(2,4),(3,3),(4,2),(5,1).
So:
count=5\boxed{count=5}

54. Search with loops

Suppose we search numbers 1 through 100 for first multiple of both 7 and 9.
python
for x in range(1, 101):
    if x % 7 == 0 and x % 9 == 0:
        print(x)
        break
The first such value is:
63.63.

55. First vs all matches

With break:
python
if condition:
    ...
    break
you stop at the first match.
Without break, the loop can process all matches.
Choose based on the problem.

56. Existence check

Pattern:
python
found = False

for x in range(...):
    if condition:
        found = True
        break
Afterward:
python
if found:
    ...
This answers:
Does at least one qualifying value exist?

57. Universal property

Suppose we want to test:
Do all values satisfy condition?
Start:
python
all_valid = True
Then:
python
for ...:
    if not condition:
        all_valid = False
        break
One counterexample is enough to disprove a universal statement.

58. Existential vs universal logic

Exists

Initialize false:
python
found = False
Set true when one witness appears.

All

Initialize true:
python
all_valid = True
Set false when one counterexample appears.
This is a major reusable loop pattern.

59. Divisor counting

python
count = 0

for d in range(1, n + 1):
    if n % d == 0:
        count += 1
At end:
text
count = number of positive divisors of n
For prime nn:
count=2.count=2.

60. Prime check using divisor count

python
count = 0

for d in range(1, n + 1):
    if n % d == 0:
        count += 1

if count == 2:
    print("Prime")
Correct but less efficient than stopping once a nontrivial divisor is found.

python
is_prime = n > 1

for d in range(2, n):
    if n % d == 0:
        is_prime = False
        break
No need to keep checking after discovering one divisor.

62. Search range can be reduced

For prime testing, any composite integer nn has at least one factor not exceeding:
n.\sqrt n.
So an optimized algorithm can test only up to that region.
This is an example of improving an algorithm without changing the problem.

63. Repeated division

Consider:
python
count = 0

while n % 2 == 0:
    n //= 2
    count += 1
This determines how many times 2 divides the original number.
For:
n=40,n=40,
trace:
40→20→10→540\to20\to10\to5
so count:
3.3.
Because:
40=23⋅5.40=2^3\cdot5.

64. Euclidean-style repeated transformation

Loops are useful when state repeatedly shrinks.
For example, greatest-common-divisor algorithms repeatedly transform pairs until one becomes zero.
General pattern:
text
state
↓
smaller state
↓
smaller state
↓
termination condition
The important Week 5 skill is recognizing repeated-state transformation.

65. Repeated subtraction example

python
while a != b:
    if a > b:
        a -= b
    else:
        b -= a
For positive integers, this repeatedly reduces the larger value.
Eventually:
a=ba=b
and that common value is the GCD.
This is a conceptual example of a condition-controlled algorithm.

66. for or while?

Use for naturally when you have:
text
for every item/value in a known sequence
Examples:
  • integers 1–100
  • exactly 10 repetitions
  • each character
  • each element of a collection
Use while naturally when:
text
repeat until condition changes
Examples:
  • until input is valid
  • until sentinel appears
  • until number becomes zero
  • until target found

67. Same problem, both forms

Print 1–5:

for

python
for i in range(1, 6):
    print(i)

while

python
i = 1

while i <= 5:
    print(i)
    i += 1
Both work.
The for version expresses the intended finite sequence more directly.

68. Loops can alter several variables

python
a = 1
b = 1

for _ in range(5):
    a = a + b
    b = b + 1
Trace carefully because the second statement sees the updated a only if it refers to a.
Assignments happen sequentially.

69. Update order matters

Compare:
python
a = a + b
b = a - b
with:
python
b = a - b
a = a + b
These are generally different algorithms.
Inside loops, small ordering differences accumulate across iterations.

70. Fibonacci-style update issue

Suppose:
a=0,b=1.a=0,\quad b=1.
Naively:
python
a = b
b = a + b
After first assignment:
a=1.a=1.
Then second uses new a, giving:
b=2,b=2,
not the desired next Fibonacci pair (1,1)(1,1).

71. Preserve old state

One approach:
python
old_a = a
a = b
b = old_a + b
Or Python simultaneous assignment:
python
a, b = b, a + b
The right-hand side is evaluated before the assignments are applied.

72. Fibonacci generation

python
a = 0
b = 1

for _ in range(6):
    print(a)
    a, b = b, a + b
Outputs:
text
0
1
1
2
3
5

73. Running maximum

python
maximum = first_value

for ...:
    if x > maximum:
        maximum = x
Invariant:
maximum equals the largest processed value so far.

74. Running second-order state

Some loop problems require more than one historical value.
Examples:
text
previous
current
or:
text
largest
second_largest
The key is updating them in the correct order so old information is not destroyed prematurely.

75. Pattern: previous value

python
previous = int(input())

for _ in range(n - 1):
    current = int(input())

    if current < previous:
        ...
    
    previous = current
This can detect relationships between consecutive inputs.

76. Check increasing sequence

python
increasing = True
previous = int(input())

for _ in range(n - 1):
    current = int(input())

    if current <= previous:
        increasing = False

    previous = current
At the end, increasing tells whether every new value was larger than the previous one.

77. Why update previous last

You need old previous for the comparison:
python
current <= previous
Only after that comparison should:
python
previous = current
prepare state for the next iteration.

78. Nested-loop pattern: rectangle

python
for i in range(3):
    for j in range(5):
        print("*", end="")
    print()
Output:
text
*****
*****
*****
Outer loop:
33
rows.
Inner loop:
55
characters per row.

79. Pattern: decreasing triangle

python
for i in range(5, 0, -1):
    print("*" * i)
Output:
text
*****
****
***
**
*
Sometimes one loop plus string repetition is enough; nested loops are not always necessary.

80. Prefer simpler structure

If:
python
print("*" * i)
solves the problem, there may be no need for another loop.
Good programming is not about maximizing the number of loops.
It is about expressing the algorithm clearly.

Common mistake: condition never changes
python
x = 5

while x > 0:
    print(x)
Infinite.
Always identify the variable controlling the condition.

Common mistake: update before processing
Compare:
python
while x <= 5:
    print(x)
    x += 1
with:
python
while x <= 5:
    x += 1
    print(x)
Starting at 1, second version prints:
text
2 3 4 5 6
rather than:
text
1 2 3 4 5
Order matters.

Common mistake: sentinel accidentally included
Wrong if -1 means stop:
python
while True:
    x = int(input())
    total += x

    if x == -1:
        break
Here -1 was already added.
Better:
python
while True:
    x = int(input())

    if x == -1:
        break

    total += x

Common mistake: reuse destroyed
n
After:
python
while n > 0:
    n //= 10
the final value is typically:
0.0.
If you later need the original, save it beforehand.

Common mistake: nested-loop count is addition
For:
python
for i in range(5):
    for j in range(4):
        action
action executes:
5×4=205\times4=20
times.
Not:
5+4=9.5+4=9.
Common mistake: inner loop does not reset
In:
python
for i in range(3):
    for j in range(2):
        ...
the inner range(2) is traversed fresh for each outer iteration.
Sequence:
text
i=0 → j=0,1
i=1 → j=0,1
i=2 → j=0,1

Common mistake:
break exits every loop
No.
python
for i in ...:
    for j in ...:
        break
breaks only the inner j loop.
The outer i loop continues.

Common mistake: variable initialization inside wrong loop
Suppose counting all valid pairs.
Wrong:
python
for i in range(n):
    count = 0

    for j in range(n):
        if condition:
            count += 1
count resets for each outer iteration.
If you want one global total:
python
count = 0

for i in range(n):
    ...

Common mistake: wrong flag reset
Wrong:
python
for ...:
    found = False

    if condition:
        found = True
If found is meant to remember whether a match occurred at any point, initialize it once before the loop.

Common mistake: use
for variable after manual mutation
python
for i in range(5):
    i += 100
The next iteration still takes the next value from range(5).
Changing i does not change the range iterator.

Common mistake: assume
range creates all values conceptually at once
For problem solving, you can think of its sequence:
text
0,1,2,...
But Python's range object is designed to represent the arithmetic progression compactly rather than requiring a fully materialized list.
This distinction becomes more useful when collections arrive.

92. Trace while with a table

Program:
python
x = 3
s = 0

while x <= 12:
    s += x
    x += 3
Trace:
x befores befores afterx after
3036
6399
991812
12183015
Then:
15≤1215\leq12
is false.
Final:
s=30\boxed{s=30}

93. Trace nested loop systematically

For:
python
x = 0

for i in range(3):
    for j in range(i + 1):
        x += 1
Inner counts:
  • i=0i=0: 1
  • i=1i=1: 2
  • i=2i=2: 3
Total:
1+2+3=6.1+2+3=6.
Thus:
x=6\boxed{x=6}

94. Iteration mental checklist

When you see a loop, identify:
  1. initial state
  2. loop condition / iterable
  3. values taken by loop variable
  4. body
  5. state updates
  6. termination mechanism
  7. output
  8. whether break or continue alters normal flow
For nested loops, do this separately for outer and inner loops.

95. for checklist

For:
python
for i in range(a, b, s):
write the actual sequence first.
Do not trace the body until you know exactly what values i will take.
This eliminates many errors.

96. while checklist

For:
python
while condition:
ask:
  • What makes condition initially true?
  • Which variable controls it?
  • How does that variable change?
  • Does every execution path eventually make it false?
  • Can break terminate it?
  • Can continue skip an essential update?

97. Core Week 5 patterns

Condition-controlled repetition

python
while condition:
    ...

Sentinel loop

python
while x != sentinel:
    ...

Validation

python
while invalid:
    read_again()

Digit processing

python
while n > 0:
    digit = n % 10
    n //= 10

Nested iteration

python
for i in range(...):
    for j in range(...):
        ...
python
for ...:
    if target:
        break

98. Week 4 → Week 5 progression

Week 4:
text
repeat across a known range
Week 5:
text
repeat until state changes
+
combine multiple loops
+
solve richer iterative problems
So your iteration toolbox becomes:
text
                ITERATION
                /       \
             for        while
              |           |
          sequence     condition
              \           /
               \         /
               nested loops
                    |
          accumulators / search
                    |
             algorithmic state

99. What you should actually master

By the end of Python Week 5, you should be comfortable with:
  1. Writing and tracing while loops.
  2. Distinguishing for from while.
  3. Identifying initialization, condition, and update.
  4. Recognizing and preventing infinite loops.
  5. Using sentinel-controlled loops.
  6. Validating input with repetition.
  7. Using break.
  8. Using continue safely.
  9. Processing digits with % 10 and // 10.
  10. Computing digit sums/counts.
  11. Reversing an integer.
  12. Preserving original state when mutation destroys it.
  13. Writing nested loops.
  14. Calculating nested-loop execution counts.
  15. Generating pairs and patterns.
  16. Understanding that break affects only the nearest loop.
  17. Using flags for search/existence problems.
  18. Checking universal conditions using counterexamples.
  19. Maintaining previous/current state.
  20. Updating multi-variable state in the correct order.
  21. Tracing complex iteration systematically.
  22. Handling zero-iteration and boundary cases.
If these are comfortable, Programming in Python Week 5 is under control.

Quick Recall & Flashcards

Test your active recall before proceeding to practice problems. Format:
Question :: Answer.
  • Week 5 Diagnostic: What happens when a break statement inside a loop executes? :: Answer: B — break terminates the enclosing loop immediately. In contrast, continue skips to the next iteration.
  • Week 5 Diagnostic: When does the else block attached to a for loop execute? :: Answer: C — A loop's else clause runs when the loop finishes iterating all elements without hitting a break.

Practice & Self-Check

Attempt these diagnostic questions to verify your operational understanding.
1

Question 1

What happens when a break statement inside a loop executes?
MCQ
3 Unit Assessment
A. Skips the rest of the current iteration and continues with the next
B. Immediately terminates the innermost enclosing loop
C. Exits the entire Python script
D. Restarts the loop from index 0
2

Question 2

When does the else block attached to a for loop execute?
MCQ
3 Unit Assessment
A. Always on every iteration
B. Only if the loop was terminated by a break statement
C. Only if the loop completed naturally without encountering a break
D. Only if an exception occurred

Active Recall Session

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.