Repetition With Loops
Computers shine when they do the same job thousands of times without complaint. Loops are how Python tells the machine to repeat. In this chapter we introduce the for and while loops, the break, continue and else clauses, and the iteration patterns you'll meet in every real-world Python project.
Overview
Repetition
Run the same code as many times as you need, varying inputs every iteration.
Counting & Summing
Aggregate data — totals, averages, max/min — over collections.
Iterate Anything
Walk through lists, dicts, files, network streams, generators.
Loop Control
break stops early, continue skips, pass stands still.
Nested Patterns
Combine loops to traverse 2-D structures and produce visual patterns.
Syntax
- Use
for x in iterable:to walk through every element. - Use
while condition:to repeat while a condition stays true. breakexits the nearest enclosing loop immediately.continueskips the rest of this iteration and moves on to the next.passis a no-op — useful as a placeholder.
# for-loop syntax
for item in iterable:
# do something with item
# while-loop syntax
while condition:
# do something
# remember to update the condition
# loop control
for x in data:
if x is None:
continue # skip this round
if x == 'STOP':
break # exit the loop
process(x)
Detailed Explanation
- Why we use loops: Without loops you would copy-paste the same block over and over. Loops let you write one statement that runs many times, varying inputs each round.
- The for loop:
foriterates over an iterable — anything that produces items one at a time (list, tuple, string, dict, set, file, range, generator). Python automatically stops when the iterable is exhausted. - The while loop:
whilekeeps running its body as long as a boolean expression is true. You must change something inside the body so the condition eventually becomes false — otherwise you get an infinite loop. - break, continue and pass:
breakjumps out of the loop entirely.continueshort-circuits to the next iteration.passdoes nothing — useful as a placeholder while you sketch logic. - The else clause: Python loops accept an
elseblock that runs only if the loop finishes withoutbreak. Great for search algorithms. - Nested loops: Loops inside loops let you scan grids, multiplication tables, or matrices. Watch the time complexity — a 100×100 nested loop runs 10,000 times.
Code Examples
for i in range(1, 6):
print(i)
2
3
4
5
n = 5
while n > 0:
print(n)
n -= 1
print("Liftoff!")
4
3
2
1
Liftoff!
n = 10
total = 0
for i in range(1, n + 1):
total += i
print("Sum:", total)
data = [3, 7, 11, 15, 4, 9]
for x in data:
if x % 2 == 0:
print("First even:", x)
break
nums = [4, -2, 7, -9, 6]
positive_sum = 0
for n in nums:
if n < 0:
continue
positive_sum += n
print("Sum of positives:", positive_sum)
for i in range(1, 4):
for j in range(1, 4):
print(f"{i}x{j}={i*j}", end=" ")
print()
2x1=2 2x2=4 2x3=6
3x1=3 3x2=6 3x3=9
Real-World Use Cases
Reading Files
Loop over lines in a CSV or log file to extract or summarise records.
Bulk Email
Iterate through a contact list to send personalised newsletters.
Data Aggregation
Walk through datasets to compute totals, averages and frequencies.
Sensor Polling
IoT scripts loop forever to read temperature, humidity or motion sensors.
Batch Image Processing
Resize or watermark every file in a folder using a simple for-loop.
Schedulers & Bots
While-loops keep services alive, polling for new tasks every few seconds.
Notes & Pro Tips
- Prefer
forwhen you know the iterable in advance; usewhilewhen the stopping condition is dynamic. - Always update the loop variable inside a
whilebody to avoid infinite loops. - Use
range(start, stop, step)for numeric sequences without storing the full list. - Use
enumerate(iterable)when you need both index and value. - Use
zip(a, b)to walk through two sequences in parallel. - Avoid modifying a list while iterating over it — iterate over a copy instead.
Common Mistakes
- Infinite loop: forgetting to update the condition in a
while. - Off-by-one error:
range(1, 10)stops at 9, not 10. - Mutating during iteration: deleting list items inside a for-loop changes indices unexpectedly.
- Misplaced break: breaks out of the innermost loop only, not all nested ones.
- Heavy work inside the loop: compute constants once outside the loop, not on every iteration.
- Using
range(len(x))when not needed: iterate directly withfor item in x.
Practice Problems
- Problem 1: Print the multiplication table of any number entered by the user.
- Problem 2: Count how many vowels are present in a given sentence.
- Problem 3: Read 10 numbers and print the largest and the smallest.
- Problem 4: Use a while-loop to find the factorial of a given number.
- Problem 5: Print all prime numbers between 1 and 100.
- Problem 6: Build a simple password retry script — give the user 3 chances to log in.
Interview Questions
- Q1. What is the difference between
forandwhileloops? - Q2. How does the loop
elseclause behave in Python? - Q3. Explain
break,continueandpasswith examples. - Q4. What is an infinite loop and how can you intentionally create one safely?
- Q5. What is the time complexity of nested loops?
- Q6. How would you iterate over two lists in parallel?
Frequently Asked Questions
- Q1: When should I use for vs while?
Use for when you know what to iterate over (a list, a range, a file). Use while when the loop ends based on a condition that changes during execution. - Q2: What does the loop's else block do?
It runs when the loop finishes naturally (without a break). It is commonly used to indicate that no match was found in a search loop. - Q3: How do I exit two nested loops at once?
Wrap them in a function and use return, or use a flag variable, or raise/catch an exception — Python has no labelled break. - Q4: What is the difference between break and continue?
break exits the loop entirely; continue skips the remainder of the current iteration and starts the next one. - Q5: Can I iterate a dictionary?
Yes — for key in d, for value in d.values(), or for key, value in d.items(). - Q6: Why is my while loop never ending?
Most likely the variable used in the condition is never updated inside the body. Print the value during the loop to debug.
Summary
Loops convert one-line ideas into bulk action. for walks through anything iterable, while repeats until a condition flips, and the trio of break, continue and pass let you steer the flow. With these few constructs you can process thousands of records, build games, run servers, or train models — all from short, expressive Python code.
Continue Learning
Previous
Go to Previous Chapter