I\'m about 2 weeks deep in my study of Python as an introductory language. I\'ve hit a point in Zed\'s \"Learn Python the Hard Way\" where he suggests:
It's because in the typical situation where you want to iterate, python can handle it for you. For example:
>>> mylist = [1,2,3,4,5,6,7]
>>> for item in mylist:
... print item
...
1
2
3
4
5
6
7
Similar example with a dictionary:
>>> mydict = {1:'a', 2:'b', 3:'c', 4:'d'}
>>> for key in mydict:
... print "%d->%s" % (key, mydict[key])
...
1->a
2->b
3->c
4->d
Using a while
loop just isn't necessary in a lot of common usage scenarios (and is not "pythonic").
Here's one comparison from a mailing list post that I though was a good illustration, too:
> 2. I know Perl is different, but there's just no equivalent of while
>($line = <A_FILE>) { }
?Python's 'for' loop has built-in knowledge about "iterable" objects, and that includes files. Try using:
for line in file: ...
which should do the trick.
This is an idiom I use frequently:
done = False
while not done:
done = DoSomeStuffAndReturnTrueIfAllDone()
# wait a while before polling again for more work
time.sleep(5)
I could pull this out into a generator, sure, but I don't see that as a win. Are there other pythonic ways to do this?
Edited to clarify that I'm periodically polling for work.
I think that using infinite loop is conceptually wrong, because an algorithm is, by its definition, composed by a finite numbers of instructions (wikipedia):
In mathematics, computer science, and related subjects, an algorithm [...] is an effective method for solving a problem expressed as a finite sequence of steps.
In my opinion is better to find another solution than the infinite loop whenever possible, and this applies to every programming language past, present and future.
Let me share a secret with you: Nine times out of ten with python, the answer is just "use common sense". It's not a terribly tricky language (aside from some notable gotchas). In this case, I'd consider Zed's rule of thumb superfluous because it's almost always common sense to know what kind of loop to use.
That said, if I run into a situation that requires iteration and I have a choice, I prefer the following (from greatest to least preference):
Comprehensions are simple, but it's surprising how many times you can make a for loop into one if you put thought into it. But generally, I'd say that about 90% of all iteration I'll do is with a list comprehension or a for loop.
>>> counter = 0
>>> while counter < 5:
print counter
counter += 1
0
1
2
3
4
>>> for x in range(5):
print x
0
1
2
3
4
See for yourself, which one do you prefer? ;)
When an easier to understand and easier to read code works, that is the Python-ic
way.
The for loop is best for looping through a collection. I mostly think of the for loop as a "definite loop." Using a for loop for a collection prevents errors arising from attempting to use indices that are out of bounds or from accidentally using negative indices. Unless you are in a special situation, use a for loop for traversing a collection.
The while loop is most useful for situations where you may have to repeat an action an indefinite number of times. It is the "indefinite loop". The example shown above for calculating a gcd is a prime example of where to use a while loop. You must bear in mind that the predicate in the while must change, or you could get stuck in an infinite loop.
If at all possible, avoid using break to get out of a loop.