Modifying a variable in a non-global outer scope?

E

Edward C. Jones

#! /usr/bin/env python
"""
When I run the following program I get the error message:

UnboundLocalError: local variable 'x' referenced before assignment

Can "inner" change the value of a variable defined in "outer"? Where
is this explained in the docs?
"""
def outer():
def inner():
x = x + 1

x = 3
inner()
print x

outer()
 
B

bruno at modulix

Edward said:
#! /usr/bin/env python
"""
When I run the following program I get the error message:

UnboundLocalError: local variable 'x' referenced before assignment

Can "inner" change the value of a variable defined in "outer"?

Not this way
Where
is this explained in the docs?
IIRC,
http://www.python.org/doc/2.4.2/ref/naming.html

"""
def outer():
def inner():
x = x + 1

x = 3
inner()
print x

outer()

What are functions arguments and return values for ?

def outer():
def inner(x):
return x+1
x = 3
x = inner(x)
print x

outer()

Using side-effects - specially this way - is a Very Bad Thing(tm). It
makes code that is hard to read and hard to maintain.
 

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

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top