Loops & Iteration Patterns
Teaching Code to Repeat
Imagine you’re a hacker testing a lock. You try one combination, then another, then another until it opens. Repetition is at the heart of problem‑solving. Without loops, you’d have to write the same instruction dozens of times. With loops, you teach your program to repeat intelligently.
Loops are the rhythm of programming. They allow your code to cycle through data, retry tasks, and automate repetitive work. This chapter is about harnessing that rhythm making your programs efficient, elegant, and unstoppable.
Why Loops Matter
- Efficiency: Loops prevent redundancy. Instead of writing 100 lines, you write one loop.
- Automation: Hackers automate repetitive tasks; loops are like the engine behind that automation.
- Iteration: Loops let you traverse collections (lists, sets, dictionaries) systematically.
- Control: With
break,continue, and conditions, you decide when loops stop or skip.
Iterating Over Collections
The for loop is Python’s way of walking through sequences.
items = ["laptop", "phone", "tablet"]
for item in items:
print(item)
- Why? Instead of manually printing each item, the loop cycles through the list automatically.
- Why?
range()generates a sequence of numbers, perfect for controlled repetition.
- Why?
Range Iteration:
for i in range(5):
print(i)
Repeat Until Breaks
The while loop continues as long as a condition is true.
count = 0
while count < 5:
print("Count:", count)
count += 1
- Why? Useful when you don’t know how many iterations are needed and when only the condition matters.
- Why? Hackers use infinite loops carefully, often with break conditions to exit.
Infinite Loops:
while True:
print("Running forever...")
break
Controlling Loops
else with Loops: Executes if the loop finishes without break.
for i in range(3):
print(i)
else:
print("Loop completed successfully.")
continue: Skips the current iteration, moves to the next.
for i in range(5):
if i == 2:
continue
print(i)
break: Stops the loop entirely.
for i in range(10):
if i == 5:
break
print(i)
Thinking Like a Hacker
- Traversing Collections: Lists, sets, and dictionaries are best explored with loops.
- Searching: Use loops to scan for values or conditions.
- Accumulation: Loops help sum values, build strings, or collect results.
- Nested Loops: For multi‑dimensional data like matrices or grids.
matrix = [[1,2,3],[4,5,6],[7,8,9]]
for row in matrix:
for value in row:
print(value, end=" ")
The Hacker’s Notebook
- Loops are the heartbeat of automation - use them to eliminate repetition.
forloops shine when iterating collections;whileloops shine when conditions drive repetition. - Control statements (
break,continue,else) give you precision over loop behavior. Nested loops unlock multi‑dimensional problem solving, but beware of complexity.
Hacker’s Mindset: treat loops as your rhythm machine. With them, you orchestrate repetition, efficiency, and control in your code.
