Python by Swaroop C H - HTML preview

PLEASE NOTE: This is an HTML preview only and some elements such as links or page numbers may be incorrect.
Download the book in PDF, ePub, Kindle for a complete version.

Using the while statement

Example 6.2. Using the while statement

#!/usr/bin/python
# Filename: while.py
number = 23
running = True
while running:
guess = int(raw_input('Enter an integer : '))

if guess == number:
print 'Congratulations, you guessed it.' running = False # this causes the while loop to stop

elif guess < number:
print 'No, it is a little higher than that.'
else:
else: print 'No, it is a little lower than that.'

print 'The while loop is over.'
# Do anything else you want to do here
print 'Done'

Output

$ python while.py
Enter an integer : 50
No, it is a little lower than that. Enter an integer : 22
No, it is a little higher than that. Enter an integer : 23
Congratulations, you guessed it. The while loop is over.
Done

How It Works

In this program, we are still playing the guessing game, but the advantage is that the user is allowed to keep guessing until he guesses correctly - there is no need to repeatedly execute the program for each guess as we have done previously. This aptly demonstrates the use of thewhile statement.

We move the raw_input andif statements to inside thewhile loop and set the variablerunning toTrue before the while loop. First, we check if the variablerunning isTrue and then proceed to execute the corresponding while-block. After this block is executed, the condition is again checked which in this case is therunning variable. If it is true, we execute the while-block again, else we continue to execute the optional else-block and then continue to the next statement.

The else block is executed when thewhile loop condition becomesFalse - this may even be the first time that the condition is checked. If there is anelse clause for awhile loop, it is always executed unless you have awhile loop which loops forever without ever breaking out!

The True andFalse are called Boolean types and you can consider them to be equivalent to the value 1 and0 respecitvely. It's important to use these where the condition or checking is important and not the actual value such as1.

The else-block is actually redundant since you can put those statements in the same block (as thewhile statement) after thewhile statement to get the same effect.

Note for C/C++ Programmers

Remember that you can have anelse clause for thewhile loop.