The Personal Web Pages of Chris X. Edwards

XED's Python Lessons for Beginners

--------------------------

Lesson Six - While You're Studying

To introduce code blocks I showed the `if` statement and some conditional expressions. Another command that requires a conditional expression and code blocks is `while`. It basically tells a Python program to "keep doing some thing until a circumstance arises that indicates it would be a good time to stop". The general form is shown in the following example:

x= 0
while x < 3:
    print "I'm only going to tell you this three times!"
    x+=1   # The '+=n' operator adds and stores. It is like x=x+n.
    

In this example, the circumstance or condition that would cause this loop to stop is the variable x being greater than or equal to 3. Of course one of the less charming types of programming bugs in any language is messing up this conditional and creating a loop that either never runs, or worse, never stops. In fact, one of my favorite and most succinct ways to make a CPU work very hard indefinitely is this on the shell command line:
$ python -c 'while 1:1/3'
    
This is a great command to leave running if you're testing your CPU monitor, or measuring power consumption, or if you're sharing a computer with people you hate. Basically what it does is to calculate the division problem of 1 divided by 3 and then does it again, and again, and again, forever. The way I'm sure that it will always execute the 1/3 whenever it gets the chance is that my conditional is simply 1. That's not much of a condition since by definition 1 is always true. I could have said 'while True:1/3' and I would get the same result because the word "True" is also always true. And, not surprisingly, 0 and "False" are always false.

Suppose you want to create an interactive program that reads user commands and acts on them.

#!/usr/bin/python
import time
usersays= raw_input("P1-enter command: ") # Prompts user for input.
while not usersays == 'quit':
    if usersays == 'year':
        print time.localtime()[0]
    elif usersays == 'month':
        print time.localtime()[1]
    else:
        print "Problem: I only know 'year', 'month', and 'quit'."
        usersays= raw_input('P2-enter command: ')
        continue
    print "OK!"
    usersays= raw_input('P3-enter command: ')
print "Bye!"
    

This program works like this when run:

P1-enter command: year
2008
OK!
P3-enter command: dang
Problem: I only know 'year', 'month', and 'quit'.
P2-enter command: month
6
OK!
P3-enter command: quit
Bye!
    

Unfortunately, to accomplish this, the program must ask for the input before the loop (P1) and once again within the loop (P3). I also demonstrate the use of the `continue` function which immediately starts the next cycle of the loop it's in. This requires yet another redundant input command (P2).

Sometimes infinite loops provide a reasonable solution. The previous program does not use an infinite loop structure, but rather checks the condition of the `while` for exactly what we're looking for, i.e. did the user enter quit. The following program does the exact same thing but only uses a single `raw_input()` function call to get the user's wishes.

#!/usr/bin/python
import time
while True:
    usersays= raw_input("enter command: ")
    if usersays == "year":
        print time.localtime()[0]
    elif usersays == "month":
        print time.localtime()[1]
    elif usersays == "quit":
       break
    else:
        print "Problem: I only know 'year', 'month', and 'quit'."
        continue
    print "OK!"
print "Bye!"
    

This uses an infinite `while` loop that gets broken explicitly with the `break` command. The `break` command immediately takes control of the program to the next statement following the loop block, printing "Bye!" in this case.

While it may seem more logical to explicitly put your loop condition as the condition of the `while` statement, it often works out better to use a `break` command to terminate the loop from some point within. There are many ways to do loops and I have just shown some common variations. Hopefully you understand how Python's primary conditional looping mechanism works and are getting an appreciation for the flexibility it offers.

--------------------------
Previous LWM Home Python Lessons Index Next
This page was created with only free, open-source, publicly licensed software.
This page was designed to be viewed with any browser on any system.
Chris X. Edwards ~ June 2008