syntax error on nonlocal statement in Python

前端 未结 2 549
温柔的废话
温柔的废话 2021-01-11 12:59

I would like to test the example of the use of the nonlocal statement specified in the answer on this question:

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


        
2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-11 13:16

    Names listed in a nonlocal statement must not collide with pre-existing bindings in the local scope.

    https://docs.python.org/3/reference/simple_stmts.html#the-nonlocal-statement

    def outer():
        x = 1
        def inner():
            nonlocal x
            y = 2
            x = y
            print("inner: ", x)
        inner()
        print("outer: ", x)
    >>> outer()
    inner:  2
    outer:  2

提交回复
热议问题