局部变量在Python嵌套函数中的使用

2024-06-24 13:46:48 发布

您现在位置:Python中文网/ 问答频道 /正文

你能告诉我在下面的代码中犯了什么错误吗

def sumOfLeftLeaves(num):

    mytotal = 0

    def helper():
        mytotal = mytotal + num

    helper()
    return mytotal

inum = 100
print(sumOfLeftLeaves(inum))

Tags: 代码helperreturndef错误numprintinum
2条回答

您应该在helper函数中执行var声明,该函数实际上没有返回任何内容:

def sumOfLeftLeaves(num):

    mytotal = 0

    def helper(mytotal, num):
        mytotal = mytotal + num
        return mytotal

    return helper(mytotal, num)

inum = 100
print(sumOfLeftLeaves(inum))

不能将变量赋值给超出范围的变量(但可以读取它)。Python在当前范围中查找变量,但没有找到它,从而引发UnboundLocalError

最直接的解决方案是nonlocal关键字:

def sumOfLeftLeaves(num):

    mytotal = 0

    def helper():
        nonlocal mytotal
        mytotal = mytotal + num

    helper()
    return mytotal

inum = 100
print(sumOfLeftLeaves(inum))

但这是不好的做法。首选方法是将变量作为参数传递并返回结果。这个例子是为了简化而设计的(显然你是在递归地遍历一个二叉树),所以没有明显的重写是有点荒谬的

相关问题 更多 >