Python has two loops and beginners often pick between them by coin flip. There is a cleaner way to decide, and it fits in one question.
Ask this first
Do I already know what I am looping over?
- If yes, use a
forloop. - If no, and you are waiting for some condition to become true, use a
whileloop.
That single question settles nine cases out of ten.
for: loop over a known collection
A for loop walks through the items of something that already exists: a list of records, the lines of a file, a range of numbers, the characters in a string. You do not manage a counter yourself, and you cannot forget to move it forward, which is the whole appeal.
If you can finish the sentence "for each _____ in my _____", you want a for loop. For each line in the file. For each patient in the list. For each number from one to ten.
while: loop until something changes
A while loop keeps going as long as a condition stays true, and you do not know in advance how many times that will be. Read input until the user types "quit". Keep retrying until the connection succeeds. Keep halving the number until it reaches one.
The catch, and the reason while bites beginners more often, is that you are responsible for making the condition eventually become false. If nothing inside the loop changes what the condition tests, the loop runs forever.
while whose body forgot to move toward the finish line. Before you run one, find the line that will eventually make the condition false.The counter case, and why for usually wins
New programmers often write a while with a counter they increment by hand:
Set a counter to zero, loop while it is below ten, add one each time.
That works, but it is three chances to make a mistake: forgetting to start the counter, testing the wrong limit, forgetting to add one. A for loop over a range does all three for you and cannot drift. When you see a hand-managed counter, it is usually a for loop in disguise.
Breaking out and skipping
Both loops understand two words. break leaves the loop immediately. continue skips the rest of this pass and goes straight to the next one. These let a for loop stop early when it finds what it wanted, and let a while loop ignore an item without ending.
Where to go next
Loops are where a program stops doing one thing and starts doing many, so they are worth real practice rather than a quick skim. Loops (for / while) teaches both from scratch with examples you can run, and because loops usually wrap a decision, Making Decisions (if / elif / else) pairs naturally with it.