strange unbound local error?

R

righes

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
 
P

Pablo Ziliani

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?

Hi Enrico,

You need to say that you will be modifying the variable in the global
scope, like this:

spam = 42

def eggs():
global spam # <--here
print spam
spam = spam + 1

if __name__=="__main__":
eggs()


This can help you:
http://www.pasteur.fr/recherche/unites/sis/formation/python/ch04.html


Pablo
 
T

thebjorn

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
 

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
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top