"Chris Stromberger" <bi*********@hotmail.com> schrieb im Newsbeitrag
news:l2********************************@4ax.com...
This doesn't seem like it should behave as it does without using
"global d" in mod().
d = {}
def mod():
d['hey'] = 3
mod()
print d
When run, it prints {'hey': 3}. Seems like it should print {} w/o
using "global d".
Can someone explain? I guess it has to do with the fact that I'm not
reassigning the name d in the function, but it seems counter-intuitive
that I'm able to modify a global inside the function w/o saying
"global d".
Well Chris, it *may* be counter-intuitive. On the other hand it is very
consequent. Think of what happens in an _ordinary_ programming language when
you use a name in a block or subroutine:
- either it is locally defined/declared: the loccal version is taken
- if it is not, the global version is used
- if there is no global version, an error message is issued.
Just the same with Python!
But do we define/declare variables in Python? Yes, by simply assigning a
value to them!
In case of your list note that you do not assign a new value to _d_ but to
just to one of it's items.
Kindly
Michael P