Skip to main content

Control Flow

Loops

Complete lesson for Loops using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Python data structures and OOP where relevant.

L1

Basics — Loops

Section: Control Flow. Master Python loops: for, while, range, enumerate, nested loops, break, continue, and else on loops.

What are loops?

  • A loop repeats a block of code while a condition holds or while items remain in a sequence.
  • Python’s main loop forms are for (iterate a sequence / iterable) and while (repeat while a condition is true).
  • Use for when you already have something to walk (list, str, range, file lines). Use while when you stop on a condition that is not a fixed count.
  • Real life: print every student in a roll list (for), keep asking for a password until it is correct (while).

Syntax: for, while, for-each & nested loops

Loops repeat Python statements while a condition holds or while items remain. Each form below shows the syntax and a short example. Python has no do-while — use while True with break when you need the body to run at least once.

for + range

Syntax

for i in range(stop):
    # statements

Example

for i in range(3):
    print(i)
# Output:
# 0
# 1
# 2

while

Syntax

while condition:
    # statements
    # update the condition

Example

n = 3
while n > 0:
    print(n)
    n -= 1
# Output:
# 3
# 2
# 1

for-each

Syntax

for item in iterable:
    # statements

Example

for ch in "hi":
    print(ch)
# Output:
# h
# i

nested loops

Syntax

for outer in iterable:
    for inner in iterable:
        # statements

Example

for row in range(2):
    for col in range(2):
        print(row, col)
# Output:
# 0 0
# 0 1
# 1 0
# 1 1
  • for + range: known count — for i in range(3):.
  • while: entry-controlled — may run zero times; update the condition variable.
  • for-each: visit every element in a list, string, or other iterable.
  • nested: inner loop finishes fully for each outer step (tables, grids).

for loop and iterables

  • for item in iterable: binds item to each successive value and runs the indented body.
  • Strings, lists, tuples, sets, dicts (keys), range, and open files are all iterable.
  • The loop variable is just a name; reassigning it does not change the original sequence.
  • Indentation defines the body — usually 4 spaces. A missing colon or wrong indent is a common beginner error.
for ch in "hi":
    print(ch)
# Output:
# h
# i

range — counting loops

  • range(stop) yields 0 .. stop-1. range(start, stop) and range(start, stop, step) add start and step.
  • range is lazy: it does not build a full list in memory (Python 3).
  • Stop is exclusive. range(1, 5) is 1, 2, 3, 4 — not 5.
  • Negative step walks downward: range(5, 0, -1) → 5, 4, 3, 2, 1.
print(*range(1, 4))
# Output:
# 1 2 3

while loop

  • while condition: runs the body as long as condition is truthy.
  • You must update variables inside the body or the loop never ends.
  • Prefer while for “repeat until done” problems: digit processing, menus, retries.
  • Empty body needs pass if you only need a placeholder.
n = 3
while n > 0:
    print(n)
    n -= 1
# Output:
# 3
# 2
# 1

break, continue, and pass

  • break exits the nearest enclosing loop immediately.
  • continue skips the rest of the body and goes to the next iteration.
  • pass is a no-op placeholder where a statement is required by syntax.
  • In a while, if you continue, make sure the counter/update still runs or you can spin forever.
vals = []
for i in range(1, 6):
    if i == 3:
        continue
    if i == 5:
        break
    vals.append(i)
print(*vals)
# Output:
# 1 2 4

else on loops

  • A for/while may have an else: block that runs when the loop finishes normally.
  • If the loop exits via break, the else is skipped.
  • Classic use: search — else means “not found”.
  • This is Python-specific; many languages have no loop-else.
for n in [2, 4, 6]:
    if n % 2 != 0:
        break
else:
    print("all even")
# Output:
# all even

enumerate and zip

  • enumerate(seq, start=0) yields (index, value) pairs — prefer it over range(len(seq)) when you need both.
  • zip(a, b) walks two (or more) iterables in parallel and stops at the shortest.
  • zip(*matrix) can transpose a list of equal-length rows.
  • In Python 3.10+, zip(..., strict=True) errors if lengths differ.
names = ["Ann", "Bob"]
for i, name in enumerate(names, start=1):
    print(i, name)
# Output:
# 1 Ann
# 2 Bob

Nested loops

  • A loop inside another loop is nested. Inner runs fully for each outer iteration.
  • Use clear names (row/col) instead of reusing one i.
  • Nested loops over n × n are O(n²) — say that in interviews.
  • A plain break only exits the inner loop; use a flag, return, or restructure to leave both.
PatternTypical use
for over rangeCounting, indexes, tables
for over sequenceProcess each element
while + updateUnknown iteration count
Nested forGrids, patterns, pairs
L2

Advanced — Loops

Loop performance and style

  • Prefer iterating the sequence directly: for x in xs beats for i in range(len(xs)) unless you need the index.
  • Building strings with += in a tight loop is slow; collect parts in a list and "".join(parts).
  • while True: plus break is fine for menus and servers when the exit condition is clearer that way.
  • for over a mutating list while removing items is unsafe; iterate a copy or build a new list.

Infinite loops and sentinels

  • while True: is an intentional infinite loop — always plan a break/return exit.
  • Sentinel values (e.g. read until empty string) pair well with while.
  • KeyboardInterrupt (Ctrl+C) stops a runaway loop in the REPL or a script.
  • Avoid busy-wait loops without sleep in real apps; they burn CPU.
total = 0
for x in [10, 20, 0, 5]:
    if x == 0:
        break
    total += x
print(total)
# Output:
# 30

Comprehensions vs explicit loops

  • List/dict/set comprehensions are loops under the hood, optimized for building collections.
  • Keep comprehensions simple; complex multi-branch logic belongs in a normal for.
  • Generator expressions (x*x for x in xs) are lazy — good for large or piped data.
  • Do not put side effects (prints, I/O) inside comprehensions; use a for body.

Common pitfalls

  • Off-by-one: range(n) is 0..n-1; range(1, n+1) is 1..n.
  • Modifying a list while iterating it can skip elements; iterate list(xs) or indexes carefully.
  • else on loops confuses people who expect else only with if — practice the “no break” meaning.
  • float loop counters can miss the end due to precision; prefer range with ints.
L3

Tricky Interview Points

Q1) What is the difference between for and while in Python?

Answer for iterates an iterable a known “stream” of values. while repeats while a boolean condition stays true. Prefer for for sequences and while for condition-driven repetition.

Q2) What does range(5) produce?

Answer The integers 0, 1, 2, 3, 4. Stop is exclusive. It is a range object, not a list.

Q3) How do break and continue differ?

Answer break leaves the loop entirely. continue skips the rest of the current iteration and starts the next one.

Q4) When does a loop else run?

Answer After the loop completes without hitting break. If break fires, else is skipped.

Q5) Why prefer enumerate over range(len(seq))?

Answer It is clearer, works for any iterable (not only sized sequences), and avoids manual index math.

Q6) How do you exit two nested loops?

Answer Use a flag checked by the outer loop, extract loops into a function and return, or raise/handle a custom exception. Plain break only exits the inner loop.

Q7) Is range a list?

Answer No. In Python 3, range is an immutable sequence of numbers computed lazily. Wrap with list(range(...)) if you need a real list.

Q8) What happens if a while condition never becomes false?

Answer An infinite loop. Fix by updating state, adding break, or correcting the condition.

Q9) Can you loop over a dictionary?

Answer Yes. for k in d iterates keys. Use d.values(), d.items(), or for k, v in d.items().

Q10) What is an off-by-one error in loops?

Answer Using the wrong bound so you process one too many or one too few items — often <= vs <, or forgetting stop is exclusive in range.

Q11) How does zip stop?

Answer It stops when the shortest iterable is exhausted (unless strict=True in 3.10+ raises on unequal lengths).

Q12) Should you modify a list while iterating it with for x in lst?

Answer Usually no — removals/insertions can skip or revisit items. Iterate a copy, or build a new list.

L4

Simple Programs

for — print 1 to N

n = 5
print(*range(1, n + 1))
# Output:
# 1 2 3 4 5

while — sum of digits

n = 1234
total = 0
while n > 0:
    total += n % 10
    n //= 10
print("Sum =", total)
# Output:
# Sum = 10

Nested for — star triangle

rows = 4
for r in range(1, rows + 1):
    print(*(["*"] * r))
# Output:
# *
# * *
# * * *
# * * * *

enumerate — numbered list

fruits = ["apple", "banana", "cherry"]
for i, fruit in enumerate(fruits, start=1):
    print(i, fruit)
# Output:
# 1 apple
# 2 banana
# 3 cherry

break/continue — skip and stop

vals = []
for i in range(1, 8):
    if i % 2 == 0:
        continue
    if i > 5:
        break
    vals.append(i)
print(*vals)
# Output:
# 1 3 5

loop else — search

target = 7
nums = [1, 3, 5, 9]
for n in nums:
    if n == target:
        print("found")
        break
else:
    print("not found")
# Output:
# not found
L5

Problem Solving Tricks

  • Use for x in xs unless you truly need indexes; then use enumerate.
  • Remember range stop is exclusive — range(1, n+1) prints 1..n.
  • Collect strings in a list and join once instead of += in a loop.
  • Loop else means “completed without break” — handy for search-not-found.
  • Name nested indexes row/col — never reuse one i for both levels.
  • while True + break is cleaner than a fake flag when the exit is mid-body.
  • Do not remove from a list while iterating it directly; iterate a copy.
  • Say O(n²) out loud when you write nested n×n loops in interviews.
  • Prefer //= for integer digit loops so types stay int.
  • Use zip to walk parallel lists instead of manual index pairing.
L6

Practice Programs List

  1. Print numbers 1 to N with a for and with a while.
  2. Sum digits of an integer using while and n % 10.
  3. Print a right triangle of stars with nested loops.
  4. Print the multiplication table for a given number 1..10.
  5. Count vowels in a string using a loop and continue on consonants.
  6. Find whether a target exists in a list using loop-else.
  7. Print index and value for each item with enumerate starting at 1.
  8. Pair two equal-length lists with zip and print pairs.
  9. Reverse-print a list with range(len(xs)-1, -1, -1).
  10. Simulate a 3-option menu with while True until Exit.
  11. Compute factorial of N with a for loop (no recursion).
  12. Print all pairs (i, j) with 1 ≤ i < j ≤ N using nested loops.