Python 中非本地语句的语法错误 [英] syntax error on nonlocal statement in Python

查看:23
本文介绍了Python 中非本地语句的语法错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想测试 this 问题:

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

但是当我尝试加载这段代码时,总是出现语法错误:

but when I try to load this code, I always get a syntax error:

Traceback (most recent call last):


File "<stdin>", line 1, in <module>
  File "t.py", line 4
    nonlocal x
             ^
SyntaxError: invalid syntax

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

Does anybody know what I am doing wrong here (I get the syntax error for every example that I use, containing nonlocal).

推荐答案

nonlocal 仅适用于 Python 3;它是语言的新增内容.

nonlocal only works in Python 3; it is a new addition to the language.

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

In Python 2 it'll raise a syntax error; python sees nonlocal as part of an expression instead of a statement.

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

This specific example works just fine when you actually use the correct Python version:

$ 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 中非本地语句的语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆