1. Home
  2. Computing & Technology
  3. Python

Beginning Python: Controlling the Flow

From Al Lukaszewski, for About.com

3 of 7

WHILE Loops

The while loop simply tells the computer to do something as long as the condition is met. Its syntax looks like this:

while <condition>:
    <action to be taken>
That's it. As long as the condition is met, the action is taken. For example:
a = 6
while a > 5:
    print a
    a = a - 1
This loop will execute exactly one time because, on the second pass, 'a' will not be greater than 5. If, however, the last line was omitted, an endless loop would result. If the condition is met and the criterion never changes, the action will be taken repeatedly like this:
a = 6
while a > 5:
    print "This is an endless loop!"

Explore Python
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Python

©2009 About.com, a part of The New York Times Company.

All rights reserved.