Creating while Loops


Creating while Loops

Loops are all around us. Even your shampoo bottle has looping instructions on it: "While your hair is not clean: Rinse. Lather. Repeat." This may seem like a simple idea—while some condition is true, repeat something—but it's a powerful tool in programming. It would come in quite handy, for example, in making a quiz show game. You might want to tell your program: while there are questions left, keep playing the game. Or, in a banking application, you might want to tell your program: while the user hasn't entered a valid account number, keep asking the user for an account number. The while loop lets you do exactly this.

Introducing the Three-Year-Old Simulator Program

In today's fast-paced world, many people don't get to spend the time they'd like with the children in their lives. A busy lawyer might be stuck at the office and not see her small son. A salesman might be on the road and not see his little niece. Well, the Three-Year-Old Simulator solves that problem by reproducing a conversation with a three-year-old child. The key to mimicking a three-year-old, it turns out, is the while loop. Figure 3.8 shows a sample run.

click to expand
Figure 3.8: If you've ever been in charge of a three-year-old, this should bring back warm memories.

As you can see, the program keeps asking Why? until the answer, Because., is entered. The code for the program is short:

 # Three-Year-Old Simulator # Demonstrates the while loop # Michael Dawson - 1/3/03 print "\tWelcome to the 'Three-Year-Old Simulator'\n" print "This program simulates a conversation with a three-year-old child." print "Try to stop the madness.\n" response = "" while response != "Because.":     response = raw_input("Why?\n") print "Oh. Okay." raw_input("\n\nPress the enter key to exit.") 

Examining the while Structure

The loop from the Three-Year-Old Simulator program is just two lines:

 while response != "Because.":     response = raw_input("Why? ") 

If the format of the while loop looks familiar, there's a good reason. It bears a striking resemblance to its cousin, the if structure. The only difference is that if is replaced by while. And the similarities aren't just skin-deep. In both structures, if the condition is true, the block (sometimes call the loop body in a loop) is executed. But in the while structure, the computer tests the condition and executes the block over and over, until the condition is false. That's why it's called a loop.

So, the block

     response = raw_input("Why? ") 

will continue to execute until the user enters Because.. At that point, response !="Because." is false and the loop mercifully ends. Then, the program executes the next statement, print "Oh. Okay.".

Initializing the Sentry Variable

Often, while loops are controlled by a sentry variable, a variable used in the condition and compared to some other value or values. Like a human sentry, you can think of your sentry variable as a guard, helping form a barrier around the while loop's block. In the Three-Year-Old Simulator program, the sentry variable is response. It's used in the condition and is compared to the string "Because." before the block is executed each time.

It's important to initialize your sentry variable. Most of the time, sentry variables are initialized right before the loop itself. That's what I did:

 response = "" while response != "Because.":     response = raw_input("Why? ") 

TRAP

If the sentry variable doesn't have a value when the condition is evaluated, your program will generate an error.

It's usually a good idea to initialize your sentry variables to some type of empty value. I assign "", the empty string, to response. While I could assign the string "aardvark", and the program would work just the same, it would make the code needlessly confusing.

Checking the Sentry Variable

Make sure that it's possible for the while condition to evaluate to true at some point; otherwise, the block will never run. Take, for example, one minor change to the loop you've been working with:

 response = "Because." while response != "Because.":     response = raw_input("Why? ") 

Since response is equal to "Because." right before the loop, the block will never run. The program will act like the loop isn't even there.

Updating the Sentry Variable

Once you've established your condition, initialized your sentry variable, and are sure that under some conditions the loop block will execute, you have yourself a working loop. Next, make sure the loop will end.

If you write a loop that never stops, you've created an infinite loop. Welcome to the club. At one time or another, all programmers have accidentally created an infinite loop and watched their program get stuck doing something over and over. Or they see their programs just plain freeze up.

Here's a simple example of an infinite loop:

 counter = 0 while counter <= 10   print counter 

What the programmer probably meant was for the loop to print the numbers from 0 to 10. Unfortunately, what this program does is print 0, forever. The programmer forgot to change counter, the sentry variable inside the block. So remember, the values in the condition must change inside the loop block. If they never change, the loop won't end, and you have yourself an infinite loop.




Python Programming for the Absolute Beginner
Python Programming for the Absolute Beginner, 3rd Edition
ISBN: 1435455002
EAN: 2147483647
Year: 2003
Pages: 194

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net