[Tutor] a byte of python... error with while statement?

Alan Gauld alan.gauld at blueyonder.co.uk
Fri Jun 25 02:35:34 EDT 2004


> Is there an error in the documentation or code example for
> the "while" statement?

Yes.
-----------Code-------------
number = 23
stop = False

while not stop:
        guess = int(raw_input('Enter an integer : '))

        if guess == number:
-----------Code-------------

The code above is correct.

----------Quote--------------
We move the raw_input and if statements to inside the while loop 
and set the variable stop to True before the while loop. First, 
we check the variable stop and if it is True, we proceed to 
execute the corresponding while-block. 
----------Quote--------------

The description is wrong. THe variable stop is set to *False* 
before the loop, which makes the while *test* (not stop) evaluate 
to *True", thus we execute the code block.

The author has confused himself(herself?) between the value 
of the variable and the value of the test. THis is a good 
reason to avoid negative tests where possible. It would have 
been more readable to write it as:

----------------
number = 23
start = True

while start:
        guess = int(raw_input('Enter an integer : '))

        if guess == number:

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

And would abvoid the distinction between the test and 
the variable value.

HTH,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld



More information about the Tutor mailing list