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))
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))
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.
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))