Python3: Local And Global Variables

Python3: Local And Global Variables

When we talk about local and global variables to someone, they sometimes seems bit confused. I even see developers scratching their head when they are hit by a problem in a code due to local and global variables. So here, I will try to give you a clear understanding of local and gloabal variables.

Lets say we have a variable defined:

x = 3

Now we define a function, may be a function to provide square root for any given digit as follows:

def squareRoot():
#Squaring numbers and assigning it back to variable num
x = x**x
print(x)

Now what do you think, what will happen when you call this script by following in a script?

squareRoot(x)

Hmmm, cannot think of?? Give it a try now executing the above script. What you get? Did you expect output 27 but got baffled by the error?

“UnboundLocalError: local variable ‘x’ referenced before assignment”

So if you see a error message, you will notice that error is at line:

x = x**x

So here the error statement says that we have used some variable, which has been not assigned any value. But you clearly see that you have x assigned a value of 3.

This is because you are trying to modify the variable ‘x’ by reassigning the result to it which is defined outside the function we defined i.e squareRoot. It’s basically the function squareRoot does not have a permission to modify it as it’s not defined within it’s indent block.

So if you want to have a variable modified by function, you will have to define it as a global variable which you can do by simply writing ‘global’ before the variable that you want to define as a global. So the above code can be written as:

x = 3

def squareRoot():
global x
#Squaring numbers and assigning it back to variable num
x = x**x
print(x)

squareRoot()

Now when you execute the script, it will work perfectly fine. Thats because you told your python, hey! it’s a global variable, you can modify it.

But, many school, colleges and company standards striclty restrict to use global variables. It’s considered as bad coding practice.

Now think, what if you are not allowed to use global variable, how you can make the above program still work. Well, you can make it to work by assigning a local variable value to another variable and perform operations on it as follows:

x = 3

def squareRoot():
# Assigning local variable ‘x’ value to another varaible ‘y’
y = x
#Squaring numbers and assigning it back to variable num
y = y**x
print(y)

squareRoot()

If you check above code by executing, you will notice that it still works correctly.

I hope this gives you clear understanding of local ang global variables. In case if you still have any doubt or queries, please feel free to comment here and I will try my best to solve your query and give you an answer.

Leave a Reply

Your email address will not be published. Required fields are marked *