How to use global variables inside a function

[This article was first published on Python – Predictive Hacks, and kindly contributed to python-bloggers]. (You can report issue about the content on this page here)
Want to share your content on python-bloggers? click here.

We are sure that at some point in your programming life you have received an error like UnboundLocalError: local variable ‘x’ referenced before assignment. In this post, we will show you how you can skip this error easily along with a useful hack for Pandas DataFrames.

Let’s say that we have a function that when it takes as input a negative number it returns 0. We want to apply it in a data frame but somehow we want to count how many times the function returned 0. Having said that we need a variable, let’s call it “counter”. To use this variable inside our function without any errors, we need to add this line of code: global counter (the name of the variable).

#this is out fucntion

def test(x):
    #at this point we are calling the global variable counter
    global counter
    if x<0:
        counter = counter+1

Let’s apply this function to the following DataFrame

0  -1
1   1
2  -2
3   3
4  12
5  -6
6   2
7  45
8  12
0     0
1     1
2     0
3     3
4    12
5     0
6     2
7    45
8    12

Now that the function is applied to our data frame, If we call the variable “counter” it holds how many times the function took as input a negative number.


To leave a comment for the author, please follow the link and comment on their blog: Python – Predictive Hacks.

Want to share your content on python-bloggers? click here.