递归和闭包在Python中的应用3

问题描述 投票:0回答:1

env python 3.8.2我无法得到var的值。return

def a(x):
    def b():
        nonlocal x
        if x>2:
            print(x)
            return x
        x = x + 1
        b()
    return b

print(a(1)())

结果是

4
None

我想返回x的值,但不是None,即使打印的值是None

python python-3.x recursion closures
1个回答
1
投票

返回 b(). 你第一次调用b时,它达到 b() 但什么也不返回,所以你的最终返回值是None。

def a(x):
    def b():
        nonlocal x
        if x>2:
            print(x)
            return x
        x = x + 1
        return b()
    return b

print(a(1)())
> 3
> 3
© www.soinside.com 2019 - 2024. All rights reserved.