Python Loops, nested loops, break / continue: 13 practice problems
UNIT 1 of the free Python for AI course. Read the short theory, then solve the problems below with instant tests. Python runs in your browser.
▶ Practise Loops, nested loops, break / continue nowAll topicsTheory: Loops, nested loops, break / continue in Python
THEORY
------
* for loop — iterate over ANY iterable (list, str, range, dict, file ...)
for ch in "abc": ...
for i in range(5): 0 1 2 3 4 range(start, stop, step), stop EXCLUDED
for i in range(10, 0, -2): 10 8 6 4 2
for i, x in enumerate(items, start=1): index + value
for a, b in zip(list1, list2): walk two lists together
* while loop — repeat while a condition is True (unknown number of iterations)
while n > 0:
n //= 10 # MUST change something, or it loops forever
Use while for: digits of a number, input validation, "until it converges", game loops.
* break — leave the loop immediately
continue — skip the rest of THIS iteration, go to the next
else — on a loop: runs only if the loop ended WITHOUT break ("search failed")
for x in nums:
if x < 0:
print("found"); break
else:
print("no negatives")
* Nested loops — the inner loop runs completely for EACH outer iteration.
n x m iterations -> O(n*m). Typical for: tables, grids, patterns, comparing all pairs.
for i in range(n):
for j in range(i + 1, n): # all PAIRS (i < j), each pair once
* Common LOOP PATTERNS (learn these — most problems are one of them)
accumulator total = 0; for x in xs: total += x
counter count = 0; for x in xs: if cond: count += 1
best-so-far best = xs[0]; for x in xs: if x > best: best = x
build-a-list out = []; for x in xs: out.append(f(x))
search + break for x in xs: if cond: found = x; break
digit loop while n: d = n % 10; n //= 10
* Complexity (viva): one loop over n items = O(n); nested = O(n²).
13 Loops, nested loops, break / continue practice problems
1. Reverse an Integer — while loop
Easy2 ways to solve📤 OUTPUT: return an int, e.g. 321. Use `return`, not print().
reverse_number(1230) -> 321 reverse_number(-45) -> -54
Ways: digit loop with % and // · str slicing (then try the maths way!)
Solve “Reverse an Integer — while loop” in your browser →2. Prime Check — loop + early exit
Easy2 ways to solve📤 OUTPUT: return a bool (True / False), e.g. True. Use `return`, not print().
is_prime(29) -> True is_prime(1) -> False is_prime(91) -> False (7*13)
Optimise: only test divisors up to sqrt(n) (i * i <= n). Viva: why is that enough?
Solve “Prime Check — loop + early exit” in your browser →3. All Primes up to n (inclusive)
Medium2 ways to solve📤 OUTPUT: return a list, e.g. [2, 3, 5, 7, 11, 13, 17, 19]. Use `return`, not print().
primes_up_to(20) -> [2, 3, 5, 7, 11, 13, 17, 19]
Ways: call is_prime in a loop · Sieve of Eratosthenes (much faster for big n)
Solve “All Primes up to n (inclusive)” in your browser →4. FizzBuzz (the most famous interview warm-up)
Easy2 ways to solve📤 OUTPUT: return a list, e.g. ['1', '2', 'Fizz', '4', 'Buzz']. Use `return`, not print().
Return a list for 1..n: "FizzBuzz" if divisible by 15, "Fizz" by 3, "Buzz" by 5, else str(i).
fizzbuzz(5) -> ["1", "2", "Fizz", "4", "Buzz"]
Solve “FizzBuzz (the most famous interview warm-up)” in your browser →5. Collatz Sequence — while loop
Easy2 ways to solve📤 OUTPUT: return an int, e.g. 8. Use `return`, not print().
If n is even, n = n // 2, else n = 3n + 1. Count steps until n becomes 1. n >= 1.
collatz_steps(6) -> 8 (6,3,10,5,16,8,4,2,1)
Solve “Collatz Sequence — while loop” in your browser →6. Sensor Stream — break + continue
Medium2 ways to solve📤 OUTPUT: return an int, e.g. 30. Use `return`, not print().
Real world: A sensor sends readings; -1 means "faulty reading" (skip it) and 999 means
"end of transmission" (stop, ignore everything after). Return the sum of valid readings.
sensor_total([10, -1, 20, 999, 50]) -> 30
Solve “Sensor Stream — break + continue” in your browser →7. ATM PIN Lock — loop + break + for-else
Medium2 ways to solve📤 OUTPUT: return an int or a str (text), e.g. 2. Use `return`, not print().
Real world: You get 3 tries. Return the attempt NUMBER (1-based) that matched, or "LOCKED"
if the first 3 attempts are all wrong (attempts after the 3rd are ignored).
atm_pin([1111, 1234], 1234) -> 2
atm_pin([1, 2, 3, 1234], 1234) -> "LOCKED"
Solve “ATM PIN Lock — loop + break + for-else” in your browser →8. Number Pyramid — nested loops
Easy2 ways to solve📤 OUTPUT: return a str (text), e.g. '1\n1 2\n1 2 3'. Use `return`, not print().
Return the rows joined by "\n". Row i contains 1..i separated by spaces.
number_pyramid(3) -> "1\n1 2\n1 2 3"
Solve “Number Pyramid — nested loops” in your browser →9. Pascal's Triangle (LeetCode 118) — nested loops
Medium3 ways to solve📤 OUTPUT: return a list, e.g. [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1]]. Use `return`, not print().
pascal_triangle(4) -> [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1]]
Each inner number = sum of the two numbers above it.
Solve “Pascal's Triangle (LeetCode 118) — nested loops” in your browser →10. Greatest Common Divisor — Euclid's algorithm (while loop)
Easy3 ways to solve📤 OUTPUT: return an int, e.g. 120. Use `return`, not print().
Real world: Simplifying a fraction / aspect ratio 1920x1080 -> 16:9.
gcd(1920, 1080) -> 120
Euclid: while b: a, b = b, a % b
Solve “Greatest Common Divisor — Euclid's algorithm (while loop)” in your browser →11. Armstrong Numbers in a Range
Medium2 ways to solve📤 OUTPUT: return a list, e.g. [153, 370, 371, 407]. Use `return`, not print().
A number equal to the sum of its digits each raised to the power of the number of digits.
153 = 1³ + 5³ + 3³. Return all in [low, high].
armstrong_numbers(100, 500) -> [153, 370, 371, 407]
Solve “Armstrong Numbers in a Range” in your browser →12. Loan EMI Schedule — interview at a digital-lending company
Project1 way to solve📤 OUTPUT: return a list of (month, interest, principal_paid, balance), each money value rounded to 2. Use `return`, not print().
Interviewer: "Show the borrower their month-by-month repayment table."
r = annual_rate / 12 / 100; EMI = P * r * (1 + r)**n / ((1 + r)**n - 1) (if annual_rate == 0: EMI = P / n)
Loop month 1..n: interest = balance * r; principal_paid = EMI - interest; balance -= principal_paid
Return a list of (month, interest, principal_paid, balance), each money value rounded to 2.
The last balance must be exactly 0.0 (use 0.0 when abs(balance) < 0.01).
amortization(100000, 12, 12)[0] -> (1, 1000.0, 7884.88, 92115.12)
Solve “Loan EMI Schedule — interview at a digital-lending company” in your browser →13. Stage 6 — the Scanner: split ONE line into lexemes with a while loop over characters
Compiler1 way to solve📤 OUTPUT: return a list of lexeme strings, e.g. ['let', 'x', '=', '3.5']. Use `return`, not print().
* skip spaces; stop at "#" (comment)
* number: digits with an optional ".digits" part "3.5"
* name: letter or _ then letters / digits / _ "total_1"
* string: from " to the next " (keep the quotes) '"hi you"'
unterminated -> raise SyntaxError("unterminated string")
* two-char operators FIRST: == != <= >= ** // then single: + - * / % = < > ( ) ,
* anything else -> raise SyntaxError(f"unexpected character {ch!r} at {i}")
scan("let x = 3.5 * (y+2) # comment") -> ["let", "x", "=", "3.5", "*", "(", "y", "+", "2", ")"]
Solve “Stage 6 — the Scanner: split ONE line into lexemes with a while loop over characters” in your browser →