Python Variable Scope

This article is created to cover all the things related to variable scope in Python. That is, after having careful reading and understanding this tutorial, I'm sure that, you will get to know everything about variable scope. This article deals with:

  • Python local variables with example
  • Python nonlocal keyword with example
  • Python global variables with example

Python Local Variables

All variables that are declared inside a function or class are local variables. Or you can say that a variable inside a function or class are considered as local variable only if they appear in the left side of an assignment statement (=, +=, -= etc.). For example, if you found any variable in a way like a = 5 or for a in range(5) or some other binding, then the variable a is said to be a local variable.

Local variable belongs to the local scope. That is, in the program given below:

def codescracker():
    num = 2
    print(num)

codescracker()

The scope of num variable is only to the function where it is defined. That is, outside the function (codescracker), the variable num is unknown/undefined. The above program produces 2 as output.

Now a question may arise in your mind that what if we use a local variable outside the function ?
Therefore I've created a program as given below, that uses local variable outside the function:

def codescracker():
    num = 2

print(num)

The above program produces an error (NameError) like shown in the snapshot given below:

python variable scope example

Now we may have another question in our mind that what if we want to access a variable created locally, all over the program ?
Then answer to this question is global keyword. You'll learn about global variable later on, in this tutorial. Now let's take a look at the example given below, of local variable in Python:

def codescracker():
    val = 10
    print("Value of variable \"val\" is", val)

val = 5
print("Value of variable \"val\" is", val)
codescracker()
print("Value of variable \"val\" is still", val)

The snapshot given below shows the sample output produced by above program:

python local variable example

As you can see from above example, the variable val with value 5 is global variable, and the same variable declared inside the function codescracker() is considered as local variable. Therefore the value 10 is initialized to it, is local and holds only until the execution of that function. That is, when you exit from that function, the value 10 gets lost and 5 will be the original value of variable val.

Python nonlocal Keyword

Since Python does not allows us to re-assign a new value to a variable from outer scope in an inner scope. Therefore to overcome this problem, Python provides a keyword named nonlocal. This keyword is used, when we need to perform any assignment operation to a variable that is already declared inside the outer function. For example, the following Python program:

def outer_fun():
    num = 10
    def inner_fun():
        num = num + 2
        print(num)
    inner_fun()

outer_fun()

produces an UnboundLocalError like shown in the snapshot given below:

python local variable scope

This is because, if there is an assignment to a variable inside a function, then that variable is considered as a local variable. Therefore we must have to create that variable using nonlocal keyword like shown in the program given below:

def outer_fun():
    num = 10
    def inner_fun():
        nonlocal num
        num = num + 2
        print(num)
    inner_fun()

outer_fun()

Now this time, the output produced looks like:

python variable scope

That is 12 is the output produced by above program, without producing any error. But if you do not need to perform any assignment to the variable num (a previously created variable), then you can proceed without further declaring the variable like shown in the program given below:

def outer_fun():
    num = 10
    def inner_fun():
        print(num)
    inner_fun()

outer_fun()

The output produced by this program is 10, not 12, because I've not incremented its value by 2 as done in previous program.

Note - If you found any nonlocal a variable, then this variable belongs to an enclosing function. That is neither said to be local nor global.

Python Global Variables

A global variable can be created in Python using two ways. The first way is to define variable outside from all the functions and classes, that is inside the main program. And the second way is to define variable anywhere in the program using global keyword. Here is an example of Python global variable:

def codescracker():
    global val
    val = 10
    print("Value of variable \"val\" is", val)

val = 5
print("Value of variable \"val\" is", val)
codescracker()
print("Now the Value of variable \"val\" is", val)

The snapshot given below taken, from the output produced by above Python program:

python global variable example

Here is another example created two global variables, one using normal way (inside main program) and second using global keyword as told above:

num = 10

def codes():
    print(num)

def cracker():
    global val
    val = 12
    print(val)

def codescracker():
    print(val)

print(num)
codes()
cracker()
print(val)
codescracker()

The output produced by above program is:

python global variable scope

The above program works in a way that:

  • First a variable num is created and initialized with 10
  • Since this variable is created outside any function or class, therefore the variable's scope is global
  • Because the variable's scope is global, therefore from any function or class, we can access this variable
  • I've defined two methods named codes() and cracker(). But the program flow goes to print(num) statement (that is outside both the function), after executing the first statement, that was num = 10
  • Using the print(num) statement, the value of num, that is equal to 10, gets printed on output
  • Now the statement codes() gets executed
  • That is, the method codes() gets called, and inside this method, a statement, print(num) gets executed
  • Since num is globally defined, therefore again the value of num gets printed on output, from inside the method named codes
  • Now the method cracker() gets called. Inside this method, a variable named val gets defined using global keyword
  • Since the variable is defined using global keyword, therefore this variable can be accessed from anywhere in the whole program
  • Now 12 gets assigned and printed using print(val) statement
  • And at second last, the print(val) statement gets executed, that prints 12 on output.
  • Point to be noted that the second last statement accessed a variable val that was defined inside cracker() method. This is happened, because I've used global keyword to define the variable
  • And since the variable val is defined with global keyword, therefore it can also be accessed from within another function like shown in the above program. That is, codescracker() also gets accessed to the variable val

Python Local Vs Global Variable Example Program

This is the example that you need to understand. After understanding this program, I'm sure, you'll get the complete understanding about local and global variables in Python.

val = 50

def read_from_global():
    print("\nI am inside the local scope of read_from_global().")
    print("Value of the variable \"val\" is",val)

def local():
    val = 100
    print("\nI am inside the local scope of local().")
    print("Value of the variable \"val\" is",val)

def change_global_variable():
    global val
    val = 100
    print("\nI am inside the local scope of change_global_variable().")
    print("Value of the variable \"val\" is",val)

print("\nI am in the global scope.")
print("Value of the variable \"val\" is",val)

read_from_global()
print("\nI'm back in the global scope.")
print("Value of the variable \"val\" is still",val)

local()
print("\nI'm again back in the global scope.")
print("Value of the variable \"val\" is still",val)

change_global_variable()
print("\nI'm again back in the global scope.")
print("Now this time, the value of the variable val becomes",val)

Here is its sample output:

python local vs global variable example

Python Variable Scope Example

This example program may clears all your remaining doubt (if any) about local and global variables along with nonlocal keyword:

num = 10

def codes():
    num = 200
    print("2. ",num)
    def inner():
        nonlocal num
        num = num + 50
        print("3. ",num)
    inner()
    print("4. ",num)

def cracker():
    global val
    val = 20
    print("5. ",val)
    print("6. ",num)

def codescracker():
    print("7. ",val)

print("1. ",num)
codes()
cracker()
codescracker()
print("8. ",val)

The number is provided for each print statement, that shows serial number that the print statement gets executed. The snapshot given below, taken from the output produced by above program:

python local global variables scope

Take a deep look at above program. May be, it will take few minutes. But I'm sure that, it will provides you everything about variable scope in Python.

Python Online Test


« Previous Tutorial Next Tutorial »