1

Possible Duplicate:
Why avoid while loops?

I am trying to learn Python by following Learn Python The Hard Way and as I have progressed along I found it mentioned on the site that,

Use a while-loop only to loop forever, and that means probably never. This only applies to Python, other languages are different.

Now I am basically a Java developer and this got me wondering as to why while should be avoided in python although it is widely used in Java. I haven't been able to find any answer on the internet.

Community
  • 1
  • 1
Anurag Ramdasan
  • 4,189
  • 4
  • 31
  • 53

6 Answers6

3

That statement is highly subjective and I am not sure I'd agree with it. It is easy to have an infinite loop using while in Python:

  while True:
       # do stuff

Perhaps the author was comparing this with C where it is also easy to have an infinite loop with for:

  for(;;)
      /* do stuff */

No such corresponding construct really exists for Python.

Having said there there are plenty of instances where an infinite loop is useful (in any language) - think event loops, or where the loop control can be simplified by having an infinite loop and only certain conditions causing a break.

Frequently you'll be processing sequences such as list and strings and the use of a for-loop will be a natural fit, but I'd not dismiss the while-loop simply because of that.

Levon
  • 138,105
  • 33
  • 200
  • 191
  • 1
    but does while loop cause any sort of disadvantage to the code at all? – Anurag Ramdasan Jul 03 '12 at 10:57
  • 1
    @AnuragRamdasan Not that I see .. though of course any ill-chosen language construct can. I.e., if your problem calls for a `for`-loop and you use a `while` it may not be the best choice, but it would still be workable. From a technical point of view I don't see a disadvantage. – Levon Jul 03 '12 at 10:59
3

He says in Exercise 33:

Here's the problem with while-loops: Sometimes they do not stop.

It's not really a Python problem if you know what you are doing. ;)

David Cain
  • 16,484
  • 14
  • 65
  • 75
Tobas
  • 351
  • 1
  • 6
1

No freaking idea. As a matter of fact, while is the only "classical" way of looping in Python because for is the analoque of foreach in other languages (i.e. an operator that iterates over collections or iterators).

Zaur Nasibov
  • 22,280
  • 12
  • 56
  • 83
1

There is nothing wrong with the while loop in Python, and it has its place when you are not dealing with an iterable.

But if you are dealing with an iterable (and this concept is very pervasive in Python), a for loop is always the better construct.

For example, in many languages you wold write something like:

while(! file.EOF) {
    ...
}

In Python you use:

for line in file:
    do_something_with(line)
Paulo Scardine
  • 73,447
  • 11
  • 124
  • 153
1

Learn Python The Hard Way is fairly opinionated, so I wouldn't take this to mean you should never use while. My best guess is that because iterators are a pervasive pattern in Python, most actual iteration can make use of for..in. Java had the old Iterator pattern of using while (it.hasNext()) { … }, or something similar for reading JDBC ResultSets, or from reading lines from standard input – all of which are doable with a for..in in Python. (Doable and arguably should be done; for..in is more readable, and yield makes it easy to write regular iterables, so there's little reason for a library not to expose an iterator API.)

millimoose
  • 39,073
  • 9
  • 82
  • 134
1

for is pretty much the "default" choice in Python when you want to iterate a definite number of times. For example:

for i in xrange(10):
    #do stuff
    #iterates 10 times

for an_element in a_collection:
    #do stuff
    #iterates over every element in a collection
    #though generators can be "infinite"

However, if you want to loop over code an indefinite number of times, a while loop is more idiomatic.

while a_boolean: 
    #do stuff
    #iterates as long as a_boolean evaluates to True

while True:
    #do stuff
    #iterates till a break is encountered

Since you come from a Java background, a while loop in Python is pretty much the same as a while loop in Java and is used in much the same way. A for loop in Python is like:

 for(Integer i : anArrayListOfIntegers){
     //do stuff
 }

The for(int i=0;i<10;i++) form doesn't exist in Python, you use the range()/xrange() form in the first example instead. That said, every for loop can be replaced with an equivalent while loop except in the case of list comprehensions/generator expressions and the like.

There are no real advantages or disadvantages to doing this in terms of speed or memory usage. However, Python programmers tend to use for when they are iterating over collections and while when they want to iterate while or until a condition is true. If you stick to this general rule of thumb, you probably won't go wrong.

Chinmay Kanchi
  • 62,729
  • 22
  • 87
  • 114