| [ Web Proxy ] |
| Viewing: https://wiki.python.org/moin/../python/platforms/../gui/../getting-started/WhileLoop.html | [Back] [Original] |
Legacy Wiki Page
This page was migrated from the old MoinMoin-based wiki. Information may be outdated or no longer applicable. For current documentation, see python.org.
When do I use them?
While loops, like the ForLoop, are used for repeating sections of code - but unlike a for loop, the while loop will not run n times, but until a defined condition is no longer met. If the condition is initially false, the loop body will not be executed at all.
As the for loop in Python is so powerful, while is rarely used, except in cases where a users input is required*, for example:
n = raw_input("Please enter 'hello':")
while n.strip() != 'hello':
n = raw_input("Please enter 'hello':")
However, the problem with the above code is that its wasteful. In fact, what you will see a lot of in Python is the following:
while True:
n = raw_input("Please enter 'hello':")
if n.strip() == 'hello':
break
As you can see, this compacts the whole thing into a piece of code managed entirely by the while loop. Having True as a condition ensures that the code runs until its broken by n.strip() equaling 'hello'.
Another version you may see of this type of loop uses while1 instead of whileTrue. In older Python versions True was not available, but nowadays is preferred for readability.
Starting with Py2.3, the interpreter optimized while1 to just a single jump. Using 1 was minutely faster, since True was not a keyword and might have been given a different value, which the interpreter had to look up, as opposed to loading a constant. As a programmer, it is up to you which style to use - but always remember that readability is important, and that while speed is also important, readability trumps it except in cases where timings are significantly different.
Starting in Python 3, True, False, and None are keywords, so using while1 no longer provides the tiny performance benefit used to justify it in earlier versions.
See also: http://stackoverflow.com/questions/3815359/while-1-vs-for-whiletrue-why-is-there-a-difference
* If this were Wikipedia, the above statement would be followed by citation needed.
Back to top2026, Python Software Foundation
Made with Sphinx and Shibuya theme.
| Web Proxy Viewer | New URL | Original Page |