[Tutor] fish or fowl?

Sean 'Shaleh' Perry shalehperry@attbi.com
Thu, 03 Jan 2002 08:19:21 -0800 (PST)


> 
> I get a prompt, and upon entering "f", foo is printed. Very nice, very
> convenient. Now, here's the question: how does the raw_input() call actually
> get evaluated? Is there a variable assignment going on in the background? As
> if I had typed:
> 
>>>> input_string = raw_input()
>>>> if input_string == "f": print "foo"
> 
> Or is there some other behaviour? Can I retrieve the value afterwards? I
> guess I am just curious what happens under the hood here. 
> 

python separate expressions from statements.  In some other languages (C, perl)
you can do:

if (input = raw_input()) == "f":
    print "foo"
    handle_input(input)

in python assignment is not valid in a test condition.

So, another way to approach this (and you see it in other places in python):

input = raw_input()
if input == "f":
    print "foo"
    handle_input(input)

Which you may recognize as being similar to the read a line from a file idiom
that was common before the 2.x series:


line = f.readline()
if line:
    parse_line(line)

and also:

while 1:
    line = f.readline()
    if not line: break
    parse_line(line)

which confused some new coders who were expecting:

while (line = f.readline()):
    parse_line(line)

Hope this helps.