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.
- 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).
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.
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)
| Argument | Meaning | Default |
|---|---|---|
| start | First number generated — included. | 0 |
| stop | Value at which generation halts — never included. | (required) |
| step | Amount added after each number. May be negative to count down. Cannot be 0. | 1 |
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.
| Form | Example | Generates |
|---|---|---|
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 step | range(10, 0, −2) | 10, 8, 6, 4, 2 |
| empty range | range(5, 5) | (nothing) |
| reverse count-down | range(5, 0, −1) | 5, 4, 3, 2, 1 |
# 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
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.
while condition:loop body
while:
n = 1 # initial state while n <= 5: # continuation test print(n) n += 1 # progress step
15.2.1 Flowchart of a while loop
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 foreverPress 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 for ↔ while — 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 = startwhile i < stop: (use > when step is negative)# loop bodyi += step
| Task | for version | Equivalent 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 |
| Situation | Preferred loop |
|---|---|
| Exact iteration count is known in advance | for with range() |
| Iterating over every item of a list / string / tuple / dict | for item in collection: |
| Stop when some condition becomes False (unknown count) | while condition: |
| Input validation — "keep asking until the answer is valid" | while |
15.4 break and continue
break vs continue at a glance:
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.
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 breakOutput:
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.
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.
for variable in sequence:loop body (may contain
break)else:runs only if the loop was NOT broken
nobreak.
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)
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 listWithout
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.
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 → primeNo flag variable needed. If the loop completes without finding a divisor, the
else runs and declares the number prime.
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")
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.
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 rowOutput:
1 2 3 4 5 2 4 6 8 10 3 6 9 12 15
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.
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.
for i in range(1, 6): print("*" * i)Output:
* ** *** **** *****
for i in range(5, 0, -1): for j in range(1, i+1): print(j, end="") print()Output:
12345 1234 123 12 1
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
- 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.
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.
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 + bFor
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
| Task | Code pattern |
|---|---|
| Repeat n times | for _ in range(n): |
| Count 1 to n | for i in range(1, n+1): |
| Count down from n to 1 | for i in range(n, 0, -1): |
| Every item of a list | for x in lst: |
| Index + item of a list | for i, x in enumerate(lst): |
| Loop until user types "quit" | while True: with break |
| Accumulate a sum | total = 0 then total += item inside loop |
| Accumulate a product (factorial) | prod = 1 then prod *= item |
| Skip unwanted items | if cond: continue |
| Stop early when found | if cond: break |
| "Not found" detector | for … break paired with else: "not found" |
📌 Quick Revision — Chapter 15 at a Glance
- Loop = statement that repeats a block. Python:
for(definite) andwhile(indefinite). foriterates over any sequence —range, string, list, tuple, dict, file.range(start, stop, step)— half-open: stop is never reached.stepmay be negative.- Forms:
range(stop),range(start, stop),range(start, stop, step). Default start = 0, step = 1. while— repeats while the condition isTrue. Needs an initial state, a test, and a progress step inside the body.- Forgetting to update the loop variable in a
whilecreates an infinite loop. Afor-over-rangenever 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
elseclause — runs once when the loop exits normally (sequence exhausted or condition False). Skipped if the loop was exited bybreak. 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/continueaffect 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 (withbreak). - Accumulator idiom: sum → start at 0, add each item; product → start at 1, multiply each item.