Why do I get a NameError: name 'counter' is not defined, while I set the counter variable to global?

Why do I get a NameError: name 'counter' is not defined, while I set the counter variable to global?

下面是我的代码。我不知道我做错了什么,但是当我 运行 这个时,我得到 NameError: name 'counter' is not defined。我正在从教科书中学习 Python,根据教科书,我的代码是正确的。我找不到教科书代码和这段代码的区别……我在Whosebug上看到了其他关于全局变量的问题,但我还是想不通我做错了什么。为什么会出现此错误?以及如何解决?

更新: 我知道我做错了什么。我应该在函数上面写counter = 0。

def rpower(a, n):
    'returns a to the nth power'
    global counter          # counts number of multiplications

    if n == 0:
        return 1
    # if n > 0:
    tmp = rpower(a, n//2)

    if n%2 == 0:
        counter += 1
        return tmp*tmp      # 1 multiplication

    else:
        counter += 2
        return a*tmp*tmp    # 2 multiplications

print(rpower(2, 10000))

可能是您的 counter 变量是在您之外声明的 function。喜欢:

counter=0
def rpower(a, n):
    'returns a to the nth power'
    global counter          # counts number of multiplications

    if n == 0:
        return 1
    # if n > 0:
    tmp = rpower(a, n//2)

    if n%2 == 0:
        counter += 1
        return tmp*tmp      # 1 multiplication

    else:
        counter += 2
        return a*tmp*tmp    # 2 multiplications
print(rpower(2, 10000))

我在 PyCharm 中稍微重写了您的代码。只是更改了函数的名称,因为您的代码仅通过 ctrl+v:

无法正常工作
def rpow(a, n):
global counter

if n == 0:
    return 1

tmp = rpow(a, n/2)

if n%2 == 0:
    counter += 1
    return tmp*tmp
else:
    counter += 2
    return a*tmp*tmp

打印(rpow(2, 10000))

我没有收到你的错误,但我达到了 RecursionError: maximum recursion depth exceeded in comparison

尝试做同样的事情。