How to Teach Python "Variables"

greg greg at cosc.canterbury.ac.nz
Tue Nov 27 02:29:08 EST 2007


Hrvoje Niksic wrote:
> A C programmer
> told that Python variables internally hold pointers expects this code:
> 
> def func(a):
>   a = 10
> ...
> func(x)
> 
> to change the value of x.

He shouldn't expect that, because that's not what the
equivalent code would do in C. To get that effect in C,
you would (among other things) have to write the
call as

   func(&x)

which you can't do, because there is no & operator in
Python.

I would probably use the term "reference", and explain
it by saying that a reference is a pointer to an object.
Also that Python variables always hold references, never
objects; a reference always refers to an entire object,
never a part of an object or another variable; and that
assignment is always reference assignment and never
copies objects.

And illustrate everything with lots of drawings of
boxes and arrows. It's much easier to explain all these
things unambiguously with diagrams than with words
that may not mean the same thing to the listener that
they mean to you.

--
Greg



More information about the Python-list mailing list