Teaching python (programming) to children

Huaiyu Zhu huaiyu at gauss.almadan.ibm.com
Tue Nov 6 20:50:56 EST 2001


On 6 Nov 2001 14:28:26 -0800, Hung Jung Lu <hungjunglu at yahoo.com> wrote:
>#---------------------
>def flipflop(x):
>    if x == []:
>        x.append(1)
>    else:
>        x = []
>
>a = []
>flipflop(a)
>print a
>flipflop(a)
>print a
>#---------------------
>output:
>[1]
>[1]
>
>In the above example, the 'global' statement plays no role. Nested
>scope is not the problem. Not understanding the namespace mechanism is
>the problem.
>
>The root of the non-trivialness is the namespace structure, not any
>particular Python statement or keyword. If you think you can explain
>to beginners the above example, more than a few dozen times, without
>getting exhausted, then I think you will be highly admired. :)

You are confused about the cause of this problem.  It is has nothing to do
with namespace.  It is no more complicated than the following

>>> a = []
>>> x = a  
>>> x.append(1)
>>> print a
[1]
>>> x = []
>>> print a
[1]

What is going on?  Well, remember the following two points:

1. Python distinguishes between names and objects.  So when you see names
   like a, x, ask yourself whether they refer to the same object.

2. Python distinguishes between mutation and name-binding.  Mutating an
   object will show the result in all names that point to this object.
   Rebinding a name to another object will not affect other names, even if
   they refer to the same object before.

These two points should be easily explainable to newbies using simple
analogies, such as tags tied to objects with strings.

feeling-exhausted-explaining-this-many-times-ly yr's

Huaiyu



More information about the Python-list mailing list