Confusion re "global" statement

C

Chris Stromberger

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".

Thanks,
Chris
 
M

Michael Peuser

Chris Stromberger said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top