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.
That statement is highly subjective and I am not sure I’d agree with it. It is easy to have an infinite loop using
whilein Python:Perhaps the author was comparing this with C where it is also easy to have an infinite loop with for:
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.