Differences between revisions 5 and 6
Revision 5 as of 2017-03-31 23:19:56
Size: 1938
Editor: MarkZiesemer
Comment: Account for Python 3 performance improvement.
Revision 6 as of 2017-03-31 23:23:08
Size: 2052
Editor: MarkZiesemer
Comment:
Deletions are marked like this. Additions are marked like this.
Line 26: Line 26:
   * See also: [[http://stackoverflow.com/questions/3815359/while-1-vs-for-whiletrue-why-is-there-a-difference]]

While loops

Usage in Python

  • 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 met. 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'.

  • Another version you may see of this type of loop uses while 1 instead of while True. This was due to past performance tweaks that are no longer relevant in current Python versions, and True is preferred for readability.

WhileLoop (last edited 2017-04-10 16:43:34 by SteveHolden)

Unable to edit the page? See the FrontPage for instructions.