sinha-shaurya
sinha-shaurya

Reputation: 577

Refer to variables outside a function python

I am writing a Python function to find the sum of all nodes in a binary tree,simply by using inorder traversal, something like this:

sum=0
def tree_sum(root):
    if root!=None:
        tree_sum(root.left)
        sum=sum+root.data
        tree_sum(root.right)

I am getting the following error though:

sum=sum+root.data
UnboundLocalError: local variable 'sum' referenced before assignment

Is there a reason why I am not able to reference the variable sum in this case? I did similar stuff(referencing variables in such a fashion) in Jupyter notebooks and it works.

Upvotes: 0

Views: 644

Answers (2)

user12065892
user12065892

Reputation:

it's not a good idea to use the variable name as sum. coz, python has a built-in function for sum

Yet you can try like this:

sum=0
def tree_sum(root):
    global sum
    if root!=None:
        tree_sum(root.left)
        sum=sum+root.data
        tree_sum(root.right)

or try like this:

total=0
def tree_sum(root):
    global total
    if root!=None:
        tree_sum(root.left)
        total=total+root.data
        tree_sum(root.right)

or simply make it reusable making a return

def tree_sum(root):
    total = 0
    if root!=None:
        tree_sum(root.left)
        total=total+root.data
        tree_sum(root.right)
     return total

Upvotes: 1

enzo
enzo

Reputation: 11496

First, don't name your variable sum because it'll shadow the sum built-in. I'll replace it with node_sum.

Your first node_sum is being declared on the top level, thus it's a global variable. That said, you can't change a global variable without using the global keyword inside your function:

node_sum = 0

def tree_sum(root):
    # Allow the global `node_sum` to be mutated inside this function
    global node_sum

    if root != None:
        tree_sum(root.left)
        node_sum = node_sum + root.data
        tree_sum(root.right)

However, a better practice is to not have any global variables at all. Make your tree_sum function return the sum of the current tree, and add it to a local variable node_sum:

def tree_sum(root):
    node_sum = 0

    if root != None:
        node_sum += tree_sum(root.left)
        node_sum += root.data
        node_sum += tree_sum(root.right)

    return node_sum

And then you can use it like

root = ...
print(tree_sum(root))

Upvotes: 5

Related Questions