variable question
Robert Lehmann
stargaming at gmail.com
Sat Jul 12 00:05:39 EDT 2008
On Fri, 11 Jul 2008 20:13:04 -0700, happy wrote:
> Can a variable be considered the simplest of the data structures. I am
> tutoring some kids about basics of programming using python. Not an
> expert in computer sciences, but am a python enthusiast.
Why do you need this additional layer of indirection? Just explain the
real simple data structures à la "look, kids, a string is a chain of
characters which are bytes actually. <insert explanation about encodings
etc. here>". Although explaining encodings is an *important* thing (which
many programmers still get wrong), it might be second priority to kids
and you might just want to say "a string is text" and jump into higher-
order data structures.
> I wanted to know if it is correct to say a variable is a data structure,
> it has a name and a value.
Not at all. This sounds a lot like an explanation for variables in other
languages (such as C, where the value also has a type). In Python, we use
to speak of "names," not variables. They are more like name tags you can
put on objects -- or you don't. Depending on the age/interest of your
students, I'd insert an explanation about references, reference counting
and garbage collection here (they usually find that quite understandable
and it paves the way for The Real Stuff, even though you might argue that
the refcounting gc is a CPython detail and might become obsolete with
PyPy's rise <wink>).
The important thing is really that Python's approach of references is
nearly orthogonal to the common approach of variables. In other
languages, variables are (as you described above) containers (a bucket,
really!) in your memory where you can put stuff into. Assignment is
usually a copy or pointer operation.
Python does not care at all about your memory. You have abstract objects
(incidentally saved in your memory, okay) with names being one mechanism
to reference them. Here, assignment is always a "put the left-hand side
name tag onto the right-hand side object".
> Put a stack of variables in a special data
> structure called a dictionary where the each name associates to a value.
> If in a data structure, one uses numbers starting from 0 to describe the
> name, it becomes a list and so forth....
First off, you really put objects in your data structures. Names are a
one-way mapping -- the object does not know which name tags are assigned
to it.
Your explanation of dictionaries and lists sounds a little bit upside-
down (not the mapping name->value or number->value makes it a dict or
list -- the data structure makes it a mapping with this and that
behaviour).
HTH,
--
Robert "Stargaming" Lehmann
More information about the Python-list
mailing list