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.
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) andwhile(repeat while a condition is true). - Use
forwhen you already have something to walk (list,str,range, file lines). Usewhilewhen 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:bindsitemto 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)yields0 .. stop-1.range(start, stop)andrange(start, stop, step)add start and step.rangeis 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 asconditionis truthy.- You must update variables inside the body or the loop never ends.
- Prefer
whilefor “repeat until done” problems: digit processing, menus, retries. - Empty body needs
passif you only need a placeholder.
n = 3
while n > 0:
print(n)
n -= 1
# Output:
# 3
# 2
# 1 break, continue, and pass
breakexits the nearest enclosing loop immediately.continueskips the rest of the body and goes to the next iteration.passis a no-op placeholder where a statement is required by syntax.- In a
while, if youcontinue, 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/whilemay have anelse:block that runs when the loop finishes normally. - If the loop exits via
break, theelseis skipped. - Classic use: search —
elsemeans “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 overrange(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 onei. - Nested loops over n × n are O(n²) — say that in interviews.
- A plain
breakonly exits the inner loop; use a flag,return, or restructure to leave both.
| Pattern | Typical use |
|---|---|
for over range | Counting, indexes, tables |
for over sequence | Process each element |
while + update | Unknown iteration count |
Nested for | Grids, patterns, pairs |
Advanced — Loops
Loop performance and style
- Prefer iterating the sequence directly:
for x in xsbeatsfor 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:plusbreakis fine for menus and servers when the exit condition is clearer that way.forover 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 abreak/returnexit.- 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
forbody.
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. elseon loops confuses people who expectelseonly withif— practice the “no break” meaning.floatloop counters can miss the end due to precision; preferrangewith ints.
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.
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 Problem Solving Tricks
- Use
for x in xsunless you truly need indexes; then useenumerate. - Remember
rangestop is exclusive —range(1, n+1)prints 1..n. - Collect strings in a list and
joinonce instead of+=in a loop. - Loop
elsemeans “completed withoutbreak” — handy for search-not-found. - Name nested indexes
row/col— never reuse oneifor both levels. while True+breakis 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 stayint. - Use
zipto walk parallel lists instead of manual index pairing.
Practice Programs List
- Print numbers 1 to N with a
forand with awhile. - Sum digits of an integer using
whileandn % 10. - Print a right triangle of stars with nested loops.
- Print the multiplication table for a given number 1..10.
- Count vowels in a string using a loop and
continueon consonants. - Find whether a target exists in a list using loop-
else. - Print index and value for each item with
enumeratestarting at 1. - Pair two equal-length lists with
zipand print pairs. - Reverse-print a list with
range(len(xs)-1, -1, -1). - Simulate a 3-option menu with
while Trueuntil Exit. - Compute factorial of N with a
forloop (no recursion). - Print all pairs (i, j) with 1 ≤ i < j ≤ N using nested loops.