6. Loops & Iteration
The superpower of automation
What if you needed to print the numbers 1 to 1,000? Without loops, you'd write 1,000 print() statements. With a loop, you write two lines. Loops are the mechanism by which computers do what they're built for: repeat things with incredible speed and perfect accuracy.
Every time you've used an app, seen a news feed, or run a search — loops were working behind the scenes, processing every item in a list, every row in a database, every pixel in an image.
for Loops
A for loop runs a block of code once for each item in a sequence — a list, a range of numbers, characters in a string:
while Loops
A while loop keeps running as long as a condition is True. You use it when you don't know in advance how many times you'll need to loop:
If your while condition never becomes False, your program runs forever. Always make sure something inside the loop will eventually make the condition False.
do-while Loops
Python doesn't have a built-in do-while, but the concept is: run the code once first, then check the condition. You simulate it like this:
In JavaScript, do-while exists natively and guarantees the block runs at least once:
Break & Continue
Two keywords give you fine-grained control inside loops:
Nested Loops
Loops inside loops. For every iteration of the outer loop, the inner loop runs completely:
Nested loops are used for working with grids, matrices, tables, and combinations. Be mindful: if the outer loop runs n times and the inner loop runs m times, you get n × m total iterations — this can get slow with large data.
Knowledge Check
Ready to test your understanding of 6. Loops & Iteration?