[Tutor] Python Question - Repeating output.

alan.gauld@bt.com alan.gauld@bt.com
Mon, 10 Jun 2002 22:27:04 +0100


>, the part about while. I couldn't get it, because 
> if a=0, and a=a+1, then wouldn't 0=1???</DIV>

This is a common problem for folks who speak math ;-)
In fact its so commoon some languages use a different 
symbol for assigning values such as ':='.
Thus Pascal would write your line as:

a := a+1

which is read 'a' becomes 'a' plus one.

So in python the '=' symbol doesn't mean 'is equal to' as 
in math, rather it means 'becomes' or 'takes on the value of'
and is called the 'assignment operator'

The math like equality test that you are used to is 
performed in Python with the double equal:

a == a + 1

which is always false as you would expect because 
mathematically it's nonsensical!


> a=input("Pick a number that is not lame:")<BR>
> while a==69:    # note you correctly used == here
>	 print "Good job!"
> while a !=69:
>	 print "Moron."<BR></DIV>

You only set the value of a once before going into the loop.
Try this instead:

a=input("Pick a number that is not lame:")
while a != 69:
   print 'Moron!'
   a=input("Pick a number that is not lame:")
print "Good job"

Now we change the value of a each time round the while loop.
Notice too that we only need one loop. The Good Job gets 
printed only when the while condition is false and the loop 
stops running.

> So basically - any clearer definitions of while? 

You could try my tutor under the Looping topic :-)

Basically the usual construct is:

set up initial condition(a above)
while condition:
     do something
     modify the test condition

Yours failed to change the test condition so it just 
kept on going round and round.

HTH,

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld