Iteration, while loop, and for loop

Steven D'Aprano steve at pearwood.info
Tue Jun 28 11:20:18 EDT 2016


On Tue, 28 Jun 2016 10:36 pm, Elizabeth Weiss wrote:

> Why do we use this code if we can use the simpler for loop?

Nobody with any sense would use the more complex while loop when the for
loop does the same thing.

While loops are great for loops where you don't know how many iterations
there will be but you do know that you want to keep going while some
condition applies:

while there is still work to be done:
    do some more work


But if you know how many iterations there will be, use the for loop. Even if
you don't know the number ahead of time, if you have a list of them, use a
for loop:

for each job on my todo list:
    do the job



There is a fashion, driven by "Learn Python The Hard Way", to teach people
the while loop first, because it's hard. I think that is stupid. It's like
teaching people to fly the Space Shuttle first, then saying "Ok, the Space
Shuttle is really complicated, but you can ride a bicycle instead" and then
teach them to ride a pushbike.





-- 
Steven
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list