Python中非局部语句的语法错误

Python中非局部语句的语法错误,python,syntax-error,python-nonlocal,Python,Syntax Error,Python Nonlocal,我想测试关于问题的答案中指定的非局部语句的使用示例: def outer(): x = 1 def inner(): nonlocal x x = 2 print("inner:", x) inner() print("outer:", x) 但当我尝试加载此代码时,总是会出现语法错误: Traceback (most recent call last): File "<stdin>", line 1, in &

我想测试关于问题的答案中指定的非局部语句的使用示例:

def outer():
   x = 1
   def inner():
       nonlocal x
       x = 2
       print("inner:", x)
   inner()
   print("outer:", x)
但当我尝试加载此代码时,总是会出现语法错误:

Traceback (most recent call last):


File "<stdin>", line 1, in <module>
  File "t.py", line 4
    nonlocal x
             ^
SyntaxError: invalid syntax
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“t.py”,第4行
非局部x
^
SyntaxError:无效语法

有人知道我在这里做错了什么吗(我使用的每个示例都有语法错误,包含
非本地的
)。

非本地的
仅在Python 3中有效;这是一个好主意

在Python2中,它将引发语法错误;python将
非局部
视为表达式而不是语句的一部分

当您实际使用正确的Python版本时,此特定示例工作正常:

$ python3.3
Python 3.3.0 (default, Sep 29 2012, 08:16:08) 
[GCC 4.2.1 Compatible Apple Clang 3.1 (tags/Apple/clang-318.0.58)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def outer():
...    x = 1
...    def inner():
...        nonlocal x
...        x = 2
...        print("inner:", x)
...    inner()
...    print("outer:", x)
... 
非本地语句中列出的名称不得与本地范围中预先存在的绑定冲突

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