-1

Could you advise which mistake that I made in the following code?

def sumOfLeftLeaves(num):

    mytotal = 0

    def helper():
        mytotal = mytotal + num

    helper()
    return mytotal

inum = 100
print(sumOfLeftLeaves(inum))
RSStepheni
  • 467
  • 1
  • 5
  • 6

2 Answers2

1

You can't assign to a variable out of scope (but you can read it). Python looks in the current scope for the variable and doesn't find it, raising the UnboundLocalError.

The most direct solution is the nonlocal keyword:

def sumOfLeftLeaves(num):

    mytotal = 0

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

    helper()
    return mytotal

inum = 100
print(sumOfLeftLeaves(inum))

But this is poor practice. Preferred is to pass the variable as an argument and return a result. The example is contrived for simplification (obviously you're recursively traversing a binary tree), so there's no obvious rewrite that isn't a bit absurd.

ggorlen
  • 44,755
  • 7
  • 76
  • 106
  • 1
    Good answer! I was curious about the difference between `nonlocal` and `global` and found this helpful answer: https://stackoverflow.com/questions/1261875/python-nonlocal-statement – robinovitch61 Jun 13 '19 at 22:33
0

You should do so var declaration in your helper function which actually didn't return anything:

def sumOfLeftLeaves(num):

    mytotal = 0

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

    return helper(mytotal, num)

inum = 100
print(sumOfLeftLeaves(inum))
Sebastien D
  • 4,369
  • 4
  • 18
  • 46