VM-LEARNING /class.xi ·track.cs ·ch-2-9 session: 2026_27
$cd ..

~/Iterative Statements (Loops)

root@vm-learning ~ $ open ch-2-9
UNIT 2 ▪ CHAPTER 9
15
Iterative Statements (Loops)
for · while · range() · break · continue · nested loops · suggested programs
An iterative statement — more commonly a loop — runs the same block of code over and over until some condition is satisfied. Python offers two loop constructs: for, used when you know how many times to repeat or want to visit every item of a sequence, and while, used when you want to repeat as long as a condition remains True. Loops also come with two flow-control companions — break to quit a loop early and continue to skip the current iteration. Mastery of loops is what lets you process lists of marks, compute factorials, scan files line-by-line, and generate the star patterns beloved of every CBSE exam paper.
The anatomy of any loop:
  • An initial state — something to count from, an index, an accumulator.
  • A continuation test — when does the loop stop?
  • A body — the statements to repeat, indented under the loop header.
  • A progress step — what makes the test eventually become False (so the loop ends).
A loop that forgets its progress step becomes infinite — it runs forever.
Learning Outcome 1: Write and trace Python programs that use a for loop (with range) and a while loop.

15.1 The for Loop

The for loop in Python is a definite loop — it iterates once for each item in a given sequence. That sequence can be a range of numbers, a string, a list, a tuple, a dictionary, or any other iterable.

Syntax
for  variable  in  sequence:
    loop body

15.1.1 The range() function

range() is the most common companion of a for loop — it generates a stream of integers on demand. It takes up to three arguments:

range(start, stop, step)
ArgumentMeaningDefault
startFirst number generated — included.0
stopValue at which generation halts — never included.(required)
stepAmount added after each number. May be negative to count down. Cannot be 0.1
The half-open rule. range(a, b) gives numbers from a up to but not including b. So range(1, 6) produces 1, 2, 3, 4, 5 — five values, not six.
FormExampleGenerates
range(stop)range(5)0, 1, 2, 3, 4
range(start, stop)range(2, 7)2, 3, 4, 5, 6
range(start, stop, step)range(0, 20, 5)0, 5, 10, 15
negative steprange(10, 0, −2)10, 8, 6, 4, 2
empty rangerange(5, 5)(nothing)
reverse count-downrange(5, 0, −1)5, 4, 3, 2, 1
All three forms in a single program:
# 1 — stop only
for i in range(5):
    print(i, end=" ")       # 0 1 2 3 4

# 2 — start, stop
for i in range(2, 7):
    print(i, end=" ")       # 2 3 4 5 6

# 3 — start, stop, step
for i in range(0, 20, 5):
    print(i, end=" ")       # 0 5 10 15

# 4 — count down with negative step
for i in range(10, 0, -2):
    print(i, end=" ")       # 10 8 6 4 2

15.1.2 Looping over a sequence directly

for is not restricted to range() — it works on any iterable.

# Over a string — one character at a time
for ch in "CBSE":
    print(ch)                # C  B  S  E

# Over a list
marks = [85, 72, 91, 68]
for m in marks:
    print(m, end=" ")       # 85 72 91 68

# Both index and value — use enumerate()
for i, m in enumerate(marks):
    print(i, "→", m)

15.1.3 Flowchart of a for loop

Start initialise iterator over sequence more items? (sequence exhausted?) Yes take next item → variable execute loop body repeat No Stop

15.2 The while Loop

A while loop is an indefinite loop — it repeats as long as a condition stays True. You decide in advance neither the count nor the items; you only state the stopping condition.

Syntax
while  condition:
    loop body
Example — print 1 to 5 using while:
n = 1                      # initial state
while n <= 5:               # continuation test
    print(n)
    n += 1                  # progress step

15.2.1 Flowchart of a while loop

Start initialise variable condition ? True loop body progress step (update) False Stop
Infinite loop trap. If nothing inside the loop body can eventually make the condition False, the loop never ends. Two common beginner bugs:
n = 1
while n <= 5:
    print(n)            # n never changes → hangs forever

n = 1
while n > 0:
    print(n)
    n += 1               # n only grows → hangs forever
Press Ctrl+C in the terminal to kill a runaway script. A for with range() can never be infinite — its end is fixed before the loop even starts.

15.3 forwhile — Conversion

Every for loop over range() can be rewritten as an equivalent while loop, and vice-versa. The recipe:

for i in range(start, stop, step):
    is equivalent to
  i = start
  while i < stop:   (use > when step is negative)
    # loop body
    i += step
Taskfor versionEquivalent while version
Print 0 to 4
for i in range(5):
    print(i)
i = 0
while i < 5:
    print(i)
    i += 1
Print even 0 – 20
for i in range(0, 21, 2):
    print(i)
i = 0
while i < 21:
    print(i)
    i += 2
Count down 5 → 1
for i in range(5, 0, -1):
    print(i)
i = 5
while i > 0:
    print(i)
    i -= 1
Sum 1 to 100
s = 0
for i in range(1, 101):
    s += i
s = 0
i = 1
while i < 101:
    s += i
    i += 1
SituationPreferred loop
Exact iteration count is known in advancefor with range()
Iterating over every item of a list / string / tuple / dictfor item in collection:
Stop when some condition becomes False (unknown count)while condition:
Input validation — "keep asking until the answer is valid"while
Learning Outcome 2: Use break and continue to alter the flow of a loop.

15.4 break and continue

break vs continue at a glance: break — quit the loop control jumps to the statement AFTER the loop iteration 1: normal iteration 2: if found → break iteration 3: skipped (never runs) exit first statement after the loop continue — skip the rest of THIS iteration control jumps back to the loop header for the next item iteration 1: normal iteration 2: first-half runs → continue iteration 3: normal (runs in full) next iter. The loop does NOT end — only the current iteration's body is cut short.

15.4.1 break — exit the loop early

When Python meets a break statement, it immediately leaves the enclosing loop. Any remaining iterations are abandoned.

Stop scanning as soon as a target number is found:
numbers = [3, 7, 1, 9, 2, 4]
target  = 9

for n in numbers:
    if n == target:
        print("Found!")
        break                       # abandon the rest of the list
    print("Checking", n)

print("Done")                      # runs next, after break
Output:
Checking 3
Checking 7
Checking 1
Found!
Done

15.4.2 continue — skip to the next iteration

continue skips the rest of the current iteration's body and jumps back to the loop header to take the next item. The loop itself is not abandoned.

Print only odd numbers from 1 to 10:
for n in range(1, 11):
    if n % 2 == 0:
        continue                     # skip even numbers
    print(n, end=" ")
Output: 1 3 5 7 9

15.4.3 The else clause of a loop

Python has a feature unique among popular languages: a loop can have an else clause. It runs once, after the loop finishes normally — that is, when the sequence is exhausted (for for) or the condition becomes False (for while). Crucially, the else is skipped if the loop was exited through a break.

Syntax
for  variable  in  sequence:
    loop body (may contain break)
else:
    runs only if the loop was NOT broken
Read it as "else = no break". A shorter but more accurate name would have been nobreak.
Compare — with and without break:
# Case 1 — loop finishes normally
for i in range(1, 4):
    print(i, end=" ")
else:
    print("— loop completed")

# Output:  1 2 3 — loop completed


# Case 2 — loop broken
for i in range(1, 4):
    if i == 2:
        break
    print(i, end=" ")
else:
    print("— loop completed")

# Output:  1              (else is SKIPPED — break fired)
Typical use — a "search" that reports "not found":
nums   = [3, 7, 1, 9, 2]
target = 5

for n in nums:
    if n == target:
        print("Found!")
        break
else:
    print(target, "is NOT in the list")

# Output:  5 is NOT in the list
Without for-else you would need an extra flag variable:
found = False
for n in nums:
    if n == target:
        found = True
        break
if not found:
    print(target, "is NOT in the list")
The for-else version makes the intent clearer and saves two lines.
Prime check rewritten with for-else:
n = int(input("n = "))

if n < 2:
    print(n, "is not prime")
else:
    for d in range(2, n):
        if n % d == 0:
            print(n, "is not prime")
            break
    else:
        print(n, "is prime")   # no divisor found → prime
No flag variable needed. If the loop completes without finding a divisor, the else runs and declares the number prime.
The else clause works on while loops too — same rule: it runs when the loop exits because its condition became False, and is skipped on break.
n = 10
while n > 0:
    print(n, end=" ")
    n -= 1
else:
    print("— countdown finished")
Learning Outcome 3: Write programs with nested loops.

15.5 Nested Loops

A nested loop is a loop inside another loop. The inner loop runs its full course for every single iteration of the outer one.

Multiplication table — 1 to 3, columns 1 to 5:
for i in range(1, 4):            # outer — 3 iterations
    for j in range(1, 6):        #   inner — 5 iterations (per outer)
        print(i*j, end="\t")
    print()                      # newline after each row
Output:
1	2	3	4	5
2	4	6	8	10
3	6	9	12	15
Total iterations of nested loops = (outer count) × (inner count). A 3-by-5 grid above produces 15 inner-body executions in total.
A break or continue inside the inner loop affects only that inner loop — the outer loop keeps going. Python has no direct "break out of all nested loops" keyword; you typically use a flag variable or return from a function for that.
Learning Outcome 4: Write the CBSE suggested programs — patterns, summation of series, factorial.

15.6 CBSE Suggested Programs

15.6.1 Pattern programs

Printing shape patterns is a classic exam exercise — it puts nested loops, conditional logic, and print's end="" tricks together.

Pattern 1 — Right-triangle of stars (5 rows):
for i in range(1, 6):
    print("*" * i)
Output:
*
**
***
****
*****
Pattern 2 — Descending digits:
for i in range(5, 0, -1):
    for j in range(1, i+1):
        print(j, end="")
    print()
Output:
12345
1234
123
12
1
Pattern 3 — Letter staircase:
for i in range(1, 6):
    for j in range(i):
        print(chr(65+j), end="")   # 65 = 'A'
    print()
Output:
A
AB
ABC
ABCD
ABCDE

15.6.2 Summation of a series

Compute the sum of the first n terms of   1 + x + x² + x³ + … + xⁿ. This is the classic geometric series.

# series_sum.py — sum of 1 + x + x² + ... + xⁿ

x = float(input("Value of x: "))
n = int(input("Value of n: "))

total = 0
for i in range(0, n+1):        # i = 0, 1, 2, ..., n
    total += x ** i
print(f"Sum = {total}")
Sample runs:
x = 2, n = 4   →  1 + 2 + 4 + 8 + 16 = 31.0
x = 3, n = 3   →  1 + 3 + 9 + 27    = 40.0
x = 0.5, n = 5 →  ≈ 1.96875
Many variants of this program appear in the CBSE suggested list:
  • Alternating signs:   1 − x + x² − x³ + …  — multiply each term by (-1)**i.
  • Divided series:   x + x²/2 + x³/3 + … + xⁿ/n.
  • Exponential:   x + x²/2! + x³/3! + … — combine with the factorial program below.

15.6.3 Factorial of a positive number

The factorial n! is the product 1 × 2 × 3 × … × n. By convention 0! = 1.

Using a for loop:
# factorial.py — factorial of n (non-negative)

n = int(input("n = "))

if n < 0:
    print("Factorial is not defined for negative numbers.")
else:
    fact = 1
    for i in range(1, n+1):
        fact *= i
    print(f"{n}! = {fact}")
Sample runs:
n = 0   →  0! = 1
n = 5   →  5! = 120
n = 10  →  10! = 3628800
n = -3  →  Factorial is not defined for negative numbers.
Same program using a while loop:
n = int(input("n = "))
fact = 1
i = 1
while i <= n:
    fact *= i
    i += 1
print(n, "! =", fact)

15.6.4 Bonus — Fibonacci series

Print the first n Fibonacci numbers: 0, 1, 1, 2, 3, 5, 8, 13 …

n = int(input("How many terms? "))

a, b = 0, 1
for _ in range(n):
    print(a, end=" ")
    a, b = b, a + b
For n = 8: 0 1 1 2 3 5 8 13

15.6.5 Bonus — Prime check

Classic use of break — stop as soon as you find a factor.

n = int(input("n = "))

if n < 2:
    print(n, "is not prime")
else:
    is_prime = True
    for d in range(2, n):
        if n % d == 0:
            is_prime = False
            break                    # no need to test further
    print(n, "is prime" if is_prime else "is not prime")

15.7 A Loop Cheat Sheet

TaskCode pattern
Repeat n timesfor _ in range(n):
Count 1 to nfor i in range(1, n+1):
Count down from n to 1for i in range(n, 0, -1):
Every item of a listfor x in lst:
Index + item of a listfor i, x in enumerate(lst):
Loop until user types "quit"while True: with break
Accumulate a sumtotal = 0 then total += item inside loop
Accumulate a product (factorial)prod = 1 then prod *= item
Skip unwanted itemsif cond: continue
Stop early when foundif cond: break
"Not found" detectorfor … break paired with else: "not found"

📌 Quick Revision — Chapter 15 at a Glance

  • Loop = statement that repeats a block. Python: for (definite) and while (indefinite).
  • for iterates over any sequence — range, string, list, tuple, dict, file.
  • range(start, stop, step) — half-open: stop is never reached. step may be negative.
  • Forms: range(stop), range(start, stop), range(start, stop, step). Default start = 0, step = 1.
  • while — repeats while the condition is True. Needs an initial state, a test, and a progress step inside the body.
  • Forgetting to update the loop variable in a while creates an infinite loop. A for-over-range never does.
  • Conversion: for i in range(a, b, s)i = a; while i < b: (body) i += s. Flip to > when step is negative.
  • break — abandon the loop immediately; control jumps after the loop.
  • continue — skip the rest of the current iteration; loop keeps going.
  • Loop else clause — runs once when the loop exits normally (sequence exhausted or condition False). Skipped if the loop was exited by break. Remember "else = no break". Perfect for "not found" searches.
  • Nested loops — inner loop runs fully for each outer iteration. Total body executions = outer × inner. break/continue affect only the inner loop.
  • CBSE programs: patterns (triangles, digits, letters — use nested loops + end=""), series sum (for i in range(n+1): total += x**i), factorial (fact *= i), Fibonacci (a, b = b, a+b), prime check (with break).
  • Accumulator idiom: sum → start at 0, add each item; product → start at 1, multiply each item.
🧠Practice Quiz — test yourself on this chapter