[Tutor] Python Question - Repeating output.

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Sun, 9 Jun 2002 00:11:48 -0700 (PDT)


On Sun, 9 Jun 2002, Guess Who? Me wrote:

> I downloaded python yesterday and am working through the tutorial. I got
> to http://www.honors.montana.edu/~jjc/easytut/easytut/node6.html, the
> part about while. I couldn't get it, because if a=0, and a=a+1, then
> wouldn't 0=1???

Ah!  The thing is that '=' in many programming languages does not mean
equality: in Python, it's a symbol for 'assignment'.

If it helps, if you see:

    a = a + 1

try crossing your eyes so that the '=' sign looks more like an arrow:

    a  <-- a + 1

This says, "the value of the 'a + 1' expression will be assigned into the
'a' variable."

There's a sense of time, a sense of "state" involved here that may not
jive with the math that you may be used to.  At one point, the 'a'
variable contains '0', and after executing a few statements, time passes,
and now it might contain '1'.  So it's not math: it's more like
simulation, or like scratch paper.

Dunno if that made much sense.  *grin*



> And I kept trying to make my own program with while, but they keep
> giving me infinite answers. Here's what I did:
>
> #I need an idea to make a program using "while". So I'll be lame.
> a=input("Pick a number that is not lame:")
> while a==69:
>     print "Good job!"
> while a !=69:
>     print "Moron."
> It gave me infinite "Moron." or "Good job!"s.
> So basically - any clearer definitions of while?

You had the right idea: the only problem is that the code doesn't give the
user the opportunity to revise the value of 'a'.  It's as if a child were
asking "Are we there yet?  Are we there yet?" even before the parents have
a chance to holler "Not yet".


Here's one way to fix that:

###
a = input("Pick a number that is not lame:")
while a==69:
    print "Good job!"
while a !=69:
    print "Moron."
    a = input("Play it again, Sam: ")
###


And that might help more.  Computers are stupid machinery, so they'll do
pointless things until we tell them not to.  *grin* Note that what gets
repeated in a while loop is ONLY what's indented underneath it.


Hope this helps!