Loops are fundamental control structures in programming that allow you to execute a block of code repeatedly. Instead of writing repetitive code, loops make programs efficient, concise, and easier to maintain. In Python, the primary loop constructs are for
and while
, supported by control keywords like break
, continue
, and else
.
This chapter explores Python loops in depth — including syntax, flow, nesting, loop control statements, iterables, and common mistakes. We’ll use practical examples to help you understand how to apply loops in real-world programming tasks.
Table of Contents
1. Introduction to Looping
Loops enable you to repeat an action multiple times. This is particularly useful when dealing with collections (like lists or strings), generating sequences, or automating tasks.
1.1 Use Cases:
- Iterating over elements in a list
- Repeating a task until a condition is met
- Processing user input until ‘exit’
- Generating multiplication tables, patterns
2. The for
Loop
Used to iterate over a sequence (such as a list, tuple, string, or range).
2.1 Syntax:
for item in iterable:
# block of code
2.2 Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
3. The range()
Function
Often used with for
to generate a sequence of numbers.
Syntax:
range(start, stop, step)
Examples:
for i in range(5): # 0 to 4
print(i)
for i in range(1, 10, 2): # 1 to 9, step 2
print(i)
4. Looping Through Strings
Strings are sequences, so you can loop through each character.
for char in "Python":
print(char)
5. Nested for
Loops
A loop inside another loop.
for i in range(3):
for j in range(2):
print(f"i={i}, j={j}")
Common in:
- Matrices
- Pattern printing
- Cartesian products
6. The while
Loop
Executes a block as long as a condition is true.
6.1 Syntax:
while condition:
# block of code
6.2 Example:
x = 0
while x < 5:
print(x)
x += 1
Use Cases:
- Unknown iteration counts
- Waiting for user input
- Infinite loops (with breaks)
7. Infinite Loops and Safety
Be careful not to create infinite loops:
# Dangerous!
while True:
print("Running...")
Break condition is essential:
while True:
command = input("Enter 'exit' to stop: ")
if command == 'exit':
break
8. break
Statement
Exits the loop prematurely.
for i in range(10):
if i == 5:
break
print(i)
9. continue
Statement
Skips the current iteration and continues with the next.
for i in range(5):
if i == 2:
continue
print(i)
10. else
with Loops
Python supports an optional else
block after loops, executed when the loop completes normally (not via break
).
for i in range(3):
print(i)
else:
print("Loop completed")
# Example with break
for i in range(5):
if i == 3:
break
print(i)
else:
print("This won't be printed")
11. Looping Through Dictionaries
d = {"a": 1, "b": 2, "c": 3}
# Keys
for key in d:
print(key)
# Keys and values
for key, value in d.items():
print(key, value)
12. Looping with Index: enumerate()
names = ["Alice", "Bob", "Charlie"]
for index, name in enumerate(names):
print(index, name)
13. Looping Over Multiple Sequences: zip()
names = ["Alice", "Bob"]
ages = [25, 30]
for name, age in zip(names, ages):
print(f"{name} is {age} years old")
14. Common Mistakes and Debugging Tips
- Forgetting to increment in
while
loop (causes infinite loop) - Incorrect indentation
- Using
=
instead of==
- Forgetting
break
condition
Debugging Tips:
- Use print statements to trace loop flow
- Use small ranges for testing
- Add manual exit options for infinite loops
15. Best Practices
- Keep loop blocks short and focused
- Avoid deep nesting
- Use functions to encapsulate logic
- Use
enumerate()
andzip()
when needed - Prefer
for
loops when iterating over sequences
16. Exercises
- Write a
for
loop to print numbers from 1 to 10 - Write a
while
loop that prints even numbers less than 20 - Use nested loops to print a multiplication table
- Loop through a dictionary and print key-value pairs
- Use
zip()
to pair student names and their grades - Write a program to accept user input until ‘done’ is typed
17. Summary
Loops are powerful constructs that save time and reduce code duplication. Python provides for
loops for sequence iteration and while
loops for condition-based execution. With control statements like break
, continue
, and else
, Python makes looping expressive and flexible.
Understanding how and when to use each type of loop — along with tools like enumerate()
and zip()
— empowers you to write more efficient, readable, and Pythonic code.
✅ Next Chapter: Functions in Python – Learn how to create reusable blocks of code using functions.