Loops let your Python programs execute the same block of code multiple times, eliminating tedious repetition and making your scripts more concise and maintainable. Whether you’re traversing a list of items or waiting for a condition to change, loops are the backbone of iterative tasks.
1. What Are Loops?
A loop repeatedly runs a block of code—called the loop body—until a stopping criterion is met. Instead of copying and pasting similar lines, you wrap them in a loop. This lets you:
- Process each item in a collection
- Repeat actions until a condition becomes false
- Build concise, readable algorithms for bulk operations
2. The for Loop
The for loop iterates over any iterable (lists, tuples, strings, ranges, dictionaries, sets), assigning each element to a loop variable in turn.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# apple
# banana
# cherry
- Looping over a string:
for char in "Python": print(char, end=" ") # P y t h o n - Using
range():for i in range(1, 6): # 1 to 5 print(i)range(start, stop, step)generates a sequence of numbers without building a full list in memory.
3. The while Loop
A while loop repeats as long as its condition remains True. Use it when you don’t know the exact number of iterations up front.
count = 5
while count > 0:
print("Countdown:", count)
count -= 1
# Countdown: 5
# Countdown: 4
# ... down to 1
Be careful: if the loop condition never becomes false, you’ll end up in an infinite loop.
4. Loop Control Statements
break
Immediately exit the loop, skipping any remaining iterations.
for n in range(1, 10):
if n == 5:
break
print(n)
# 1 2 3 4
continue
Skip the rest of the current iteration and move to the next.
for n in range(1, 6):
if n % 2 == 0:
continue
print(n)
# 1 3 5
else with Loops
An else block on a loop runs only if the loop completes normally (no break).
for x in [1, 2, 3]:
print(x)
else:
print("Loop finished without break.")
pass
A no-op placeholder when syntax requires a statement but you have no action yet.
for _ in range(3):
pass # TODO: implement processing later
5. Nested Loops
Place one loop inside another to handle multi-dimensional data or generate pairs/combinations.
matrix = [
[1, 2, 3],
[4, 5, 6],
]
for row in matrix:
for val in row:
print(val, end=" ")
print()
# 1 2 3
# 4 5 6
Each pass through the outer loop triggers a full run of the inner loop.
6. Looping Over Different Collections
- Lists & Tuples: direct iteration of elements.
- Dictionaries: iterates over keys—use
.items()for key/value pairs. - Sets: unordered unique items.
- Strings: individual characters.
data = {"a": 1, "b": 2}
for key, value in data.items():
print(f"{key} → {value}")
7. Best Practices
- Avoid infinite loops by ensuring your condition or loop variable changes.
- Prefer comprehensions (
[x*2 for x in nums]) for simple transformations. - Use descriptive loop variables (
for item in items:) to clarify intent. - Limit nesting to two levels; if deeper logic is needed, factor into functions.
8. Mini Project: FizzBuzz Generator
The classic FizzBuzz problem illustrates loop control and conditionals. Print numbers 1–n, but for multiples of 3 print “Fizz,” for 5 print “Buzz,” and for both print “FizzBuzz.”
def fizzbuzz(n: int):
for i in range(1, n + 1):
if i % 15 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)
if __name__ == "__main__":
fizzbuzz(20)
What You Learn:
- Combining
forloops with%checks - Using
if/elif/elseinside loops - The importance of ordering conditions (15 before 3 or 5)
Conclusion
Loops are indispensable for tasks that involve iteration, bulk processing, and dynamic repetition. By mastering the for and while constructs, leveraging control statements, and applying best practices, you can write efficient, readable Python code that scales from simple scripts to complex data pipelines. Happy looping!
Discover more from Affordable Tutor
Subscribe to get the latest posts sent to your email.


