Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Confusion re "global" statement

Reply
Thread Tools

Confusion re "global" statement

 
 
Chris Stromberger
Guest
Posts: n/a
 
      08-31-2003
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
 
Reply With Quote
 
 
 
 
Michael Peuser
Guest
Posts: n/a
 
      08-31-2003

"Chris Stromberger" <(E-Mail Removed)> schrieb im Newsbeitrag
news:(E-Mail Removed)...
> 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


 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
if statement that, when false, skips first statement in its block, executes second? Jay McGavren Java 11 01-16-2006 05:49 PM
How do I do a conditional statement in a constant statement? tkvhdl@gmail.com VHDL 3 12-16-2005 06:13 PM
Statement modifiers causing confusion Dustin McCormick Ruby 1 11-21-2005 05:27 PM
If statement confusion Drew ASP General 6 04-07-2005 02:37 PM
exec "statement" VS. exec "statement" in globals(), locals() tedsuzman Python 2 07-21-2004 08:41 PM



Advertisments