DAGDA SEARCH | Back to results | Support

While Loop - Python Wiki

Source: https://wiki.python.org/python/getting-started/WhileLoop.html

  1. Python Wiki /
  2. Python Wiki /
  3. Getting Started /
  4. While Loop
View as Markdown

While Loop

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.

While loops

Usage in Python

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 user’s 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 it’s 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 it’s broken by n.strip() equaling 'hello'.

* If this were Wikipedia, the above statement would be followed by “citation needed.”

PreviousSimple Programs Chinese Next GUI Programming