Week 5: Loop Controls & Patterns
4565 words
23 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
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)**.

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:
pythonfor i in range(...): ...
Week 5 pushes iteration further:
whileloops- condition-controlled repetition
- nested loops
- loop tracing
breakandcontinue- counters and accumulators in harder problems
- digit-processing algorithms
- repeated transformation
- searching
- patterns
- choosing
forvswhile - preventing infinite loops
The central distinction is:
versus:
1. Two major repetition styles
Count/sequence-controlled
pythonfor i in range(10): ...
You know what values drive the repetitions.
Condition-controlled
pythonwhile condition: ...
You continue until some changing condition becomes false.
2. Basic while
Syntax:
pythonwhile condition: statements
Python:
- evaluates
condition - if true, executes body
- returns to condition
- repeats
- stops when condition becomes false
3. Example
pythonx = 1 while x <= 5: print(x) x = x + 1
Output:
text1 2 3 4 5
4. Trace the state
| Iteration | x before test | Test x <= 5 | Printed | x after update |
|---|---|---|---|---|
| 1 | 1 | True | 1 | 2 |
| 2 | 2 | True | 2 | 3 |
| 3 | 3 | True | 3 | 4 |
| 4 | 4 | True | 4 | 5 |
| 5 | 5 | True | 5 | 6 |
| stop | 6 | False | — | — |
Final:
5. while has three essential pieces
A typical counter-based
while needs:Initialization
pythoni = 1
Condition
pythonwhile i <= 5:
Update
pythoni += 1
Together:
pythoni = 1 while i <= 5: print(i) i += 1
6. Missing update → infinite loop
Wrong:
pythoni = 1 while i <= 5: print(i)
i never changes.So:
pythoni <= 5
remains true forever.
Conceptually:
7. Infinite loop
An infinite loop is a loop whose termination condition is never reached.
Example:
pythonwhile 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:
pythonx = 100 while x > 0: x = x - 10
x decreases toward 0.Termination is easy to reason about.
9. Wrong update direction
pythonx = 1 while x < 10: x = x - 1
x becomes:It moves away from 10.
So condition remains true forever.
10. for equivalent
This:
pythonfor i in range(1, 6): print(i)
can be expressed:
pythoni = 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:
pythonx = int(input()) while x != 0: print(x) x = int(input())
12. Sentinel value
The special value:
text0
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:
pythontotal = 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:
text5 8 2 -1
State:
At
-1:pythonx != -1
is false.
Final:
15. Count unknown number of inputs
pythoncount = 0 x = int(input()) while x != -1: count += 1 x = int(input()) print(count)
If inputs are:
text3 9 4 7 -1
then:
16. Sum and count together
pythontotal = 0 count = 0 x = float(input()) while x != -1: total += x count += 1 x = float(input())
Then:
pythonif count > 0: average = total / count
17. Why the count > 0 check matters
Input could immediately be:
text-1
Then:
Trying:
pythontotal / count
would divide by zero.
18. Input-validation loop
while is useful when input must satisfy a condition.pythonx = int(input()) while x < 0: x = int(input())
This keeps asking until:
19. Validation example
pythonmarks = int(input()) while marks < 0 or marks > 100: marks = int(input()) print(marks)
Loop invariant after termination:
20. while True + break
Another common style:
pythonwhile 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.pythonwhile 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.pythonfor i in range(1, 6): if i == 3: continue print(i)
Output:
text1 2 4 5
23. continue in a while loop can be dangerous
Example:
pythoni = 0 while i < 5: if i == 2: continue i += 1
When:
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:
pythonx = 1 while x < 100: x = x * 2
Trace:
Then:
is false.
Final:
26. Number of iterations can be non-obvious
In:
pythonx = 1 while x < 100: x *= 2
the number of repetitions is determined by how quickly repeated doubling crosses 100.
Unlike:
pythonfor i in range(7):
the count is not explicitly written.
27. Digit processing with while
One of the most important numerical loop patterns:
pythondigit = n % 10 n = n // 10
For positive integer
n:% 10extracts last digit// 10removes last digit
28. Example
Start:
Then:
and:
Next:
So digits can be processed right-to-left.
29. Print digits in reverse order
pythonn = int(input()) while n > 0: digit = n % 10 print(digit) n = n // 10
For:
text5382
output:
text2 8 3 5
30. Sum of digits
pythonn = int(input()) total = 0 while n > 0: digit = n % 10 total += digit n //= 10 print(total)
For:
31. Trace sum of digits
n | digit | total |
|---|---|---|
| 5382 | 2 | 2 |
| 538 | 8 | 10 |
| 53 | 3 | 13 |
| 5 | 5 | 18 |
| 0 | — | stop |
Final:
32. Count digits
pythonn = int(input()) count = 0 while n > 0: count += 1 n //= 10 print(count)
For:
count:
33. Special case n = 0
The previous loop:
pythonwhile n > 0:
executes zero times when:
Yet decimal representation of 0 has one digit.
So some problems need explicit handling:
pythonif n == 0: count = 1 else: ...
Edge cases still matter inside loop algorithms.
34. Reverse a number
Suppose:
Goal:
Algorithm:
pythonreverse = 0 while n > 0: digit = n % 10 reverse = reverse * 10 + digit n //= 10
35. Reverse trace
Start:
Extract 4:
Extract 3:
Extract 2:
Extract 1:
36. Palindrome number
A number such as:
reads the same forward and backward.
Conceptual algorithm:
- save original number
- compute reverse
- compare reverse with original
pythonoriginal = 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: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.
pythonfor 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:
Inner:
Then outer:
and inner resets:
Then:
with:
40. Output
text0 0 0 1 1 0 1 1 2 0 2 1
Number of iterations:
41. General nested-loop count
pythonfor i in range(m): for j in range(n): action
action executes:times.
42. Square nested loop
pythonfor i in range(n): for j in range(n): action
executes:
times.
This connects directly to CT nested-iteration reasoning.
43. Triangle pattern
pythonfor i in range(1, 5): for j in range(i): print("*", end="") print()
Output:
text* ** *** ****
44. Why inner loop depends on i
For:
inner loop runs once.
For:
twice.
For:
three times.
So total stars:
45. Nested-loop total work
If inner count changes with outer index:
pythonfor i in range(1, n + 1): for j in range(i): ...
total executions:
46. Multiplication table grid
pythonfor i in range(1, 4): for j in range(1, 4): print(i * j, end=" ") print()
Output:
text1 2 3 2 4 6 3 6 9
Outer loop controls rows.
Inner loop controls columns.
47. Coordinate-pair generation
pythonfor i in range(3): for j in range(3): print(i, j)
visits every ordered pair:
Total:
48. Unique unordered pairs
If we need each pair once:
pythonfor i in range(n): for j in range(i + 1, n): print(i, j)
This avoids:
- self-pairs (i,i)
- duplicate reversed pairs
49. Number of unique pairs
Total:
which equals:
This is the same pair-count idea from Computational Thinking.
50. break in nested loops
Consider:
pythonfor 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=0printsj=1triggers break
So:
text0 0 1 0 2 0
Outer loop continues.
52. continue in nested loops
pythonfor i in range(3): for j in range(3): if i == j: continue print(i, j)
This skips pairs:
It processes only distinct-coordinate pairs.
53. Nested conditional filtering
Example:
pythoncount = 0 for i in range(1, 6): for j in range(1, 6): if i + j == 6: count += 1
Valid ordered pairs:
So:
54. Search with loops
Suppose we search numbers 1 through 100 for first multiple of both 7 and 9.
pythonfor x in range(1, 101): if x % 7 == 0 and x % 9 == 0: print(x) break
The first such value is:
55. First vs all matches
With
break:pythonif 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:
pythonfound = False for x in range(...): if condition: found = True break
Afterward:
pythonif found: ...
This answers:
Does at least one qualifying value exist?
57. Universal property
Suppose we want to test:
Do all values satisfy condition?
Start:
pythonall_valid = True
Then:
pythonfor ...: if not condition: all_valid = False break
One counterexample is enough to disprove a universal statement.
58. Existential vs universal logic
Exists
Initialize false:
pythonfound = False
Set true when one witness appears.
All
Initialize true:
pythonall_valid = True
Set false when one counterexample appears.
This is a major reusable loop pattern.
59. Divisor counting
pythoncount = 0 for d in range(1, n + 1): if n % d == 0: count += 1
At end:
textcount = number of positive divisors of n
For prime n:
60. Prime check using divisor count
pythoncount = 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.
61. Better prime search
pythonis_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 n has at least one factor not exceeding:
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:
pythoncount = 0 while n % 2 == 0: n //= 2 count += 1
This determines how many times 2 divides the original number.
For:
trace:
so count:
Because:
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:
textstate ↓ smaller state ↓ smaller state ↓ termination condition
The important Week 5 skill is recognizing repeated-state transformation.
65. Repeated subtraction example
pythonwhile a != b: if a > b: a -= b else: b -= a
For positive integers, this repeatedly reduces the larger value.
Eventually:
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:textfor 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:textrepeat 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
pythonfor i in range(1, 6): print(i)
while
pythoni = 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
pythona = 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:
pythona = a + b b = a - b
with:
pythonb = a - b a = a + b
These are generally different algorithms.
Inside loops, small ordering differences accumulate across iterations.
70. Fibonacci-style update issue
Suppose:
Naively:
pythona = b b = a + b
After first assignment:
Then second uses new
a, giving:not the desired next Fibonacci pair (1,1).
71. Preserve old state
One approach:
pythonold_a = a a = b b = old_a + b
Or Python simultaneous assignment:
pythona, b = b, a + b
The right-hand side is evaluated before the assignments are applied.
72. Fibonacci generation
pythona = 0 b = 1 for _ in range(6): print(a) a, b = b, a + b
Outputs:
text0 1 1 2 3 5
73. Running maximum
pythonmaximum = first_value for ...: if x > maximum: maximum = x
Invariant:
maximumequals the largest processed value so far.
74. Running second-order state
Some loop problems require more than one historical value.
Examples:
textprevious current
or:
textlargest second_largest
The key is updating them in the correct order so old information is not destroyed prematurely.
75. Pattern: previous value
pythonprevious = 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
pythonincreasing = 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:pythoncurrent <= previous
Only after that comparison should:
pythonprevious = current
prepare state for the next iteration.
78. Nested-loop pattern: rectangle
pythonfor i in range(3): for j in range(5): print("*", end="") print()
Output:
text***** ***** *****
Outer loop:
rows.
Inner loop:
characters per row.
79. Pattern: decreasing triangle
pythonfor 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:
pythonprint("*" * 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
pythonx = 5 while x > 0: print(x)
Infinite.
Always identify the variable controlling the condition.
Common mistake: update before processing
Compare:
pythonwhile x <= 5: print(x) x += 1
with:
pythonwhile x <= 5: x += 1 print(x)
Starting at 1, second version prints:
text2 3 4 5 6
rather than:
text1 2 3 4 5
Order matters.
Common mistake: sentinel accidentally included
Wrong if
-1 means stop:pythonwhile True: x = int(input()) total += x if x == -1: break
Here
-1 was already added.Better:
pythonwhile True: x = int(input()) if x == -1: break total += x
Common mistake: reuse destroyed
nAfter:
pythonwhile n > 0: n //= 10
the final value is typically:
If you later need the original, save it beforehand.
Common mistake: nested-loop count is addition
For:
pythonfor i in range(5): for j in range(4): action
action executes:times.
Not:
Common mistake: inner loop does not reset
In:
pythonfor i in range(3): for j in range(2): ...
the inner
range(2) is traversed fresh for each outer iteration.Sequence:
texti=0 → j=0,1 i=1 → j=0,1 i=2 → j=0,1
Common mistake:
break exits every loopNo.
pythonfor 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:
pythonfor 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:
pythoncount = 0 for i in range(n): ...
Common mistake: wrong flag reset
Wrong:
pythonfor ...: 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 mutationpythonfor 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 onceFor problem solving, you can think of its sequence:
text0,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:
pythonx = 3 s = 0 while x <= 12: s += x x += 3
Trace:
x before | s before | s after | x after |
|---|---|---|---|
| 3 | 0 | 3 | 6 |
| 6 | 3 | 9 | 9 |
| 9 | 9 | 18 | 12 |
| 12 | 18 | 30 | 15 |
Then:
is false.
Final:
93. Trace nested loop systematically
For:
pythonx = 0 for i in range(3): for j in range(i + 1): x += 1
Inner counts:
- i=0: 1
- i=1: 2
- i=2: 3
Total:
Thus:
94. Iteration mental checklist
When you see a loop, identify:
- initial state
- loop condition / iterable
- values taken by loop variable
- body
- state updates
- termination mechanism
- output
- whether
breakorcontinuealters normal flow
For nested loops, do this separately for outer and inner loops.
95. for checklist
For:
pythonfor 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:
pythonwhile 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
breakterminate it? - Can
continueskip an essential update?
97. Core Week 5 patterns
Condition-controlled repetition
pythonwhile condition: ...
Sentinel loop
pythonwhile x != sentinel: ...
Validation
pythonwhile invalid: read_again()
Digit processing
pythonwhile n > 0: digit = n % 10 n //= 10
Nested iteration
pythonfor i in range(...): for j in range(...): ...
Search
pythonfor ...: if target: break
98. Week 4 → Week 5 progression
Week 4:
textrepeat across a known range
Week 5:
textrepeat until state changes + combine multiple loops + solve richer iterative problems
So your iteration toolbox becomes:
textITERATION / \ 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:
- Writing and tracing
whileloops. - Distinguishing
forfromwhile. - Identifying initialization, condition, and update.
- Recognizing and preventing infinite loops.
- Using sentinel-controlled loops.
- Validating input with repetition.
- Using
break. - Using
continuesafely. - Processing digits with
% 10and// 10. - Computing digit sums/counts.
- Reversing an integer.
- Preserving original state when mutation destroys it.
- Writing nested loops.
- Calculating nested-loop execution counts.
- Generating pairs and patterns.
- Understanding that
breakaffects only the nearest loop. - Using flags for search/existence problems.
- Checking universal conditions using counterexamples.
- Maintaining previous/current state.
- Updating multi-variable state in the correct order.
- Tracing complex iteration systematically.
- 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
breakstatement inside a loop executes? :: Answer: B —breakterminates the enclosing loop immediately. In contrast,continueskips to the next iteration. - Week 5 Diagnostic: When does the
elseblock attached to aforloop execute? :: Answer: C — A loop'selseclause runs when the loop finishes iterating all elements without hitting abreak.
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 statementC. Only if the loop completed naturally without encountering a
breakD. Only if an exception occurred