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