Loops
For Loops — When You Know How Many Times
A for loop is like a tour guide walking through a group of items one by one. "Here's item 1, now item 2, now item 3..." until there's nothing left.
You can loop over anything iterable: lists, strings, ranges, dictionaries — even files. The variable after for takes on each value in turn.
For Loops & range()
While Loops — When You Don't Know How Many Times
A while loop is like a guard who keeps checking a condition: "Is it still raining? Yes → stay inside. Is it still raining? Yes → stay inside. Is it still raining? No → go outside!"
Use while when you don't know in advance how many iterations you need. Just be careful — if the condition never becomes False, you've got an infinite loop!
While Loops
Break, Continue & Enumerate
Sometimes you need more control inside a loop:
break— Stop the loop entirely. Jump out and move on. Like finding what you're looking for and leaving the store.continue— Skip this iteration and jump to the next one. Like skipping a song in a playlist.enumerate()— Gives you both the index and the value on each iteration. Super useful when you need to know the position.
Break, Continue & Enumerate
Nested Loops
You can put a loop inside another loop. Keep in mind that nested loops multiply the work — a loop inside a loop over n items runs n×n times. Understanding Big-O notation helps you reason about this.
You can also put a loop inside another loop. The inner loop runs completely for each iteration of the outer loop. Think of it like a clock: the minute hand (inner loop) goes around 60 times for every 1 tick of the hour hand (outer loop).
Nested Loops
for i in range(len(my_list)) just to get the index, stop! Use enumerate(my_list) instead. It's more Pythonic, more readable, and less error-prone.Quick check
Continue reading