python - python 中的非本地关键字错误

标签 python

我正在尝试使用nonlocal下面代码中的 python 中的关键字。 inner()包含在 outer() 中我想创建一个计数器变量来记住多少次 inner()outer() 调用。 ctr定义于 outer()以及 nonlocalinner() .

但我收到错误为 no binding for nonlocal 'ctr' found .

def inner1():
    nonlocal ctr
    ctr=ctr+1
    print(' ctr= {0}'.format(ctr))


def outer1():
    ctr=0
    for i in range(5):
        inner1()

outer1()

最佳答案

inner() is enclosed in outer()

inner 未包含在 outer 中(未在 outer 范围内定义),您仅从 outer 调用 inner;这里没有任何关闭。

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

相关文章:

python - pytest - 向所有或标记的测试函数添加断言

python代码覆盖率使用coverage.py报告分析

python - 如何让fontforge模块打印瀑布样本?

python - 如何使用 `if` 语句测试异常对象?

python - 将Python与opencv结合使用以实现图像拼接

python - Clear 和 exit_fullscreen 似乎不起作用

python - Django 迭代 ClearableFileInput 小部件字段

python - Web 抓取 html 加油站

python - 带有一些强制键作为功能输入的字典

python - 如何在 Python 中解密 AWS Ruby 客户端加密