Modifying a variable in a non-global outer scope?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Edward C. Jones

    #1

    Modifying a variable in a non-global outer scope?

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

    UnboundLocalErr or: 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()
  • bruno at modulix

    #2
    Re: Modifying a variable in a non-global outer scope?

    Edward C. Jones wrote:[color=blue]
    > #! /usr/bin/env python
    > """
    > When I run the following program I get the error message:
    >
    > UnboundLocalErr or: local variable 'x' referenced before assignment
    >
    > Can "inner" change the value of a variable defined in "outer"?[/color]

    Not this way
    [color=blue]
    > Where
    > is this explained in the docs?[/color]

    IIRC,
    The official home of the Python Programming Language

    [color=blue]
    > """
    > def outer():
    > def inner():
    > x = x + 1
    >
    > x = 3
    > inner()
    > print x
    >
    > outer()[/color]

    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.


    --
    bruno desthuilliers
    python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
    p in 'onurb@xiludom. gro'.split('@')])"

    Comment

    Working...