[Tutor] Beginner question (variables, namespaces...) (fwd)

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Sat Apr 8 18:14:02 CEST 2006


> I tried redefining the "higher-order" variables as functions, but it
> didn't quite work. Here's a simplified example:
>
>
> var1 = 2
>
> def timestwo(x):
>     return x*2
>
> var2 = timestwo(var1)
> print var1, var2
> var1 = 3
> print var1, var2

Try:

######
print 2, timestwo(2)
print 3, timestwo(3)
######


Alternatively, try:

######
var1 = 2
print var1, timestwo(var1)
var1 = 3
print var1, timestwo(var1)
######


What do you expect to see?



> ..which is not what I'm aiming for. Maybe I'll have to follow Bob's
> advice and just store all of the variable assignments in a function, and
> then call the function every time I change one of the variables (based
> on user input). I could still leave the higher-order variables as
> functions as per your advice, but that alone doesn't seem to do the
> trick. Unless I've missed something.

You're missing something.  *wink*

Play with this a little more.  It's something basic in Python, and you'll
want to get this squared away so it doesn't cause you grief later.

The model you have about how variables behave in Python is slightly off
still: I think you're still thinking of them like math equations.  But
Python's model for assigning variable names to values don't work like
equality: it's more of a "this box now contains the value described by the
right hand side at this particular time."

So if we see:

    a = 3
    b = 4
    a = a + b

we can model this as:

    [a : 3]               (after stmt: a = 3)

    [a : 3,  b : 4]      (after stmt: b = 4)

    [a : 7, b : 4]        (after stmt: a = a + b)

where we keep a list of names and their current values.  (I'm just using
an ad-hoc notation for the stuff in the brackets.)  Assignment erases the
old value and replaces it with a new one as we flow through our program.



More information about the Tutor mailing list