Loops: for, while, break, continue
You'll learn to
- -Iterate a fixed number of times with for and range()
- -Iterate directly over the items of a collection
- -Write while loops for condition-based repetition
- -Control loop flow with break and continue, and recognize for...else
Conditionals let a program branch; loops let it repeat. Almost every algorithm you'll ever write - searching, sorting, scanning - is built out of a loop doing some small piece of work over and over.
for Loops with range()
range(stop) counts from 0 up to (but not including) stop. range(start, stop) lets you pick where to begin. range(start, stop, step) adds a step size, which can even be negative to count downward. The "stops before, doesn't include" behavior of the upper bound trips up almost everyone once - range(5) gives you 5 numbers (0-4), not a 5.
for Loops Over Iterables Directly
You don't need range(len(fruits)) and then index in - Python lets you loop directly over the items of a list (and, as you'll see soon, strings, dicts, and sets too). This is the idiomatic style: reach for range() when you specifically need a sequence of numbers, and loop directly over a collection when you just need its items.
while Loops
A for loop is for "do this N times" or "do this once per item." A while loop is for "keep doing this until some condition changes" - when you don't know in advance how many iterations it'll take. Forget to update count inside the loop body and you get an infinite loop - a real risk with while that for mostly protects you from.
break and continue
break exits the loop entirely, right now, regardless of how many iterations were left. continue skips only the rest of the current iteration and moves on to the next one - the loop itself keeps running.
The for...else Quirk
This is a genuinely unusual piece of Python syntax: a for loop (or while loop) can have an else clause, and it runs only if the loop completed without hitting a break. It's a clean way to express "search for something, and if you never find it, do this" without a separate found flag variable. It's rare in the wild, but worth recognizing so it doesn't stump you the first time you see it.