Saturday, August 22, 2015

Python Basics - 013: Scope of variables: Global and local

Previous chapter: Dynamic Arguments in functions Next Chapter: Classes and Objects



Python Basics - 013: Scope of variables: Global and local


As we know variables are identifiers for data, they hold different types of data and let us access them whenever we want. There are a set of rules to use variables in different locations or context, this becomes important specially when dealing with functions.

Scope is defined as the place where the variable is accessible.

Global Variables

Variables which can be accessed anywhere in the program are called global variables.

Consider the below example:


num1 = 10

def addToNum(num2):
    print(num1+num2)

addToNum(12)

Here num1 is a variable which is outside the function, but is not a global variable. num1 can be accessed inside the function but cannot be modified. If you tried to do something like below, it would through an error.


num1 = 10

def addToNum(num2):
    num1 += 20
    print(num1+num2)

addToNum(12)

We'll get UnboundLocalError: local variable 'num1' referenced before assignment, because the num1 variable is accessible but not mutable hence the error is thrown.

The error will go away if we make num1 a global variable.

Here's how to do it.


num1 = 10

def addToNum(num2):
    global num1
    num1 += 20
    print(num1+num2)

addToNum(12)
print("num1: ", num1)

Using the global keyword we can convert the num1 into a global variable which can be modified inside the function, the changes made by the function persists outside the scope of the function too as can be seen from the output below:


42
num1:  30

Usually the global variables are not recommended by various teachers and companies because it is difficult to track changes and object oriented designs prohibit this kind of behaviour but it's nice to know how it works in normal cases.

Usually passing arguments and getting the values using return statements is the way to go.

We'll try to do the functionality using a return statement:


def addToNumber(num2):
    gnum1 = num1
    print(gnum1+num2)
    return gnum1

x = addToNumber(12)
print("num1: ", x)

We'll get the same output.


42
num1:  30

Local Variables

Local variables on the other hand exist only in the scope of the function in which they are defined. In the above example gnum1 is a local variable and it can only be used inside the addToNumber function, anywhere else in the program gnum1 doesn't exist.

We can reuse the variable name but it is generally a bad practice to do so as it might be confusing.

There's nothing much to it. Let's move on to Classes, Objects and object oriented programming.


P.S: all the code used in this tutorial is available in github




Previous chapter: Dynamic Arguments in functions Next Chapter: Classes and Objects

No comments:

Post a Comment