python - Python 中非本地语句的语法错误

标签 python syntax-error python-2.x python-nonlocal

<分区>

我想测试在this 上的答案中指定的非本地语句的使用示例。问题:

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

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

最佳答案

nonlocal 仅适用于 Python 3;这是一个new addition to the language .

在 Python 2 中它会引发语法错误; python 将 nonlocal 视为表达式而不是语句的一部分。

当您实际使用正确的 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)
... 

关于python - Python 中非本地语句的语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14264313/

相关文章:

javascript - 为什么我收到错误 "button.addEventListener is not a function"

postgresql - 找到臭名昭著的 "'”

python - 在 python 中打开 .csv 文件时语法无效

python 回合问题

python - 定期更新 Tkinter 中的标签

python - matplotlib:删除混合 2D/3D 子图中的 3D 图的空白

python - 仅比较这两个列表的变量值

python - 具有兄弟目录的 Python (3.4) 中的绝对或相对导入

python - 如何在IPython笔记本中连续显示表格后跟数字而不在末尾出现重复的数字?

php - 读取错误并修复PHP中的错误