Loops in Python
Loops allow us to repeat a block of code multiple times without writing it again.
They are essential for automating repetitive tasks and iterating over collections.
Why use loops?
- Loops save time and reduce code duplication.
- They help process lists, strings, dictionaries, and other collections efficiently.
- Used for repetitive tasks like calculations, data processing, and automation.
Examples of real-time usage:
- Iterating over a list of users to send notifications
- Processing each line in a file or CSV
- Summing numbers in a dataset
- Generating repeated patterns or reports
- Running a program until a certain condition is met (e.g., game loop, waiting for input)
We will cover:
forloops → iterate over sequences (lists, strings, ranges)whileloops → repeat while a condition is True- Nested loops → loops inside loops
- Loop control →
break,continue,pass
Example: for loop
# ---- Example: for loop ----
# Use "for" to iterate over a sequence like a list or range.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits: # 'fruit' takes each value in the list
print("I like", fruit)
# Using range() to loop over numbers
for i in range(5): # 0, 1, 2, 3, 4
print("Iteration:", i)I like apple
I like banana
I like cherry
Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Example: while loop
# ---- Example: while loop ----
# Use "while" to repeat code as long as a condition is True.
count = 0
while count < 5: # loop continues while count is less than 5
print("Count is:", count)
count += 1 # increment count to eventually stop the loopCount is: 0
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Example: nested loops
# ---- Example: nested loops ----
# A loop inside another loop. Useful for 2D data or repeated patterns.
for i in range(1, 4): # outer loop
for j in range(1, 4): # inner loop
print(f"i={i}, j={j}")i=1, j=1
i=1, j=2
i=1, j=3
i=2, j=1
i=2, j=2
i=2, j=3
i=3, j=1
i=3, j=2
i=3, j=3
Use of break
# ---- break ----
# Stops the loop immediately
for i in range(1, 6):
if i == 3:
print("Breaking loop at i =", i)
break
print(i)
# ---- continue ----
# Skips current iteration and moves to next
for i in range(1, 6):
if i == 3:
print("Skipping i =", i)
continue
print(i)
# ---- pass ----
# Does nothing, acts as a placeholder
for i in range(1, 4):
pass # can be used when loop syntax is required but no action is needed1
2
Breaking loop at i = 3
1
2
Skipping i = 3
4
5
Summary
We learned:
forloops → iterate over sequences or rangeswhileloops → repeat while a condition is True- Nested loops → one loop inside another
- Loop control:
break→ exit loopcontinue→ skip current iterationpass→ placeholder, does nothing
Next notebook: 06_functions_basics.ipynb
