Re: strange unbound local error?
- From: thebjorn <BjornSteinarFjeldPettersen@xxxxxxxxx>
- Date: Sat, 29 Sep 2007 11:24:15 -0700
On Sep 29, 8:04 pm, rig...@xxxxxxxx wrote:
hi folks,
suppose this snipplet:
spam = 42
def eggs():
print spam
spam = spam + 1
if __name__=="__main__":
eggs()
This thows an UnboundLocalError at line 4 (print statement). But if I
comment out line 5 (variable assignment), no error occurs.
Can you explain me this, please?
Regards,
Enrico
If you're going to assign to a global variable in a function, you need
to declare it as such:
spam = 42
def eggs():
global spam
print spam
spam = spam + 1
When Python sees an assignment to an identifier in a function it
creates a variable that is local to the function (otherwise you'd be
unable to create local variables with the same name as any of the
global variables).
-- bjorn
.
- References:
- strange unbound local error?
- From: righes
- strange unbound local error?
- Prev by Date: Re: strange unbound local error?
- Next by Date: Re: Program inefficiency?
- Previous by thread: Re: strange unbound local error?
- Next by thread: wxpython combined with vpython
- Index(es):
Relevant Pages
|