while Loop vs for Loop in Python: Which to Use?
for or while: Which Loop Should You Use?
Python has two loops, and many jobs can be done with either one. The rule of thumb: use for when you know what to go through, and while when you know when to stop.
Here is the same job, printing 1 to 3, both ways:
for n in range(1, 4):
print(n)1 2 3
n = 1
while n <= 3:
print(n)
n += 11 2 3
The for loop does the start, the check and the change for you, in one line. It can't forget the change, so it can't run forever by mistake. For this job, for wins.
Think of a teacher handing back tests: going through a known pile of papers is a for job. Waiting at the door until the last student arrives is a while job.
Pick the loop
| The job | Loop | Why |
|---|---|---|
| go through every item of a list or string | for | the items are known |
| repeat exactly 10 times | for with range(10) | the count is known |
| ask until the answer is valid | while | you can't know how many tries |
read until the user types done | while | the end depends on the user |
| double until over 100 | while | the number of rounds is unknown |
| count the digits of a number | while | stop when nothing is left |
A quick test
Ask yourself: "Before the loop starts, do I know how many rounds it will run, or which items it goes through?"
- Yes →
for. - No, I only know when to stop →
while.
Common beginner doubt: "Is while the worse loop, then?" Not at all. It's the only one of the two that can wait for the user, or keep going until a goal is reached. Each loop is best at its own job.
for: you know what to go through. while: you know when to stop.