Python Variable Scope



Definition


Scope of a variable in Python is the region or block of code where the variable is created.

Scope of a variable is the region of code where the variable is accessible.


Types of Scopes:

  1. Local Variable
  2. Global Variable

1. Local Scope


These are the variables that are created and accessible inside the function. These variables belong to local scope for the function inside which they are created.


Example

def aFun():
    var = "I m a local variable"
    print(var)
aFun()
print(var)

Output

I m a local variable
Traceback (most recent call last):
  File "f:/vscode/python/main.py", line 5, in <module>
    print(var)
NameError: name 'var' is not defined

2. Global Scope


These are the variables that are created in the main body of the python code and not inside a function. These variables belong to the global scope.

These variables are available within any scope, local and global.


Example

var = "I m a global variable"
def aFun():
    print(var)
aFun()
print(var)

Output

I m a global variable
I m a global variable


Function inside Function


If a function is inside another function then it can access the variable which is created inside the parent function but outside the child function.


Example

def parentFun():
    var = "I m a variable"
    print(var)
    def childFun():
        print(var)
    childFun()
parentFun()

Output

I m a variable
I m a variable

Same name with different scopes


There may be cases like when you have two variables of the same name but in different regions or scopes.

In that case, python assumes that these variables are totally different from each other and if you make changes in one variable then that change will not affect the other scope variable.


Example


var = "I m outside function"
def parentFun():
    var = "I m inside function"
    print(var)
parentFun()
print(var)

Output

I m inside function
I m outside function

Global Keyword


Python provides global keyword to create a variable that can be accessed globally.

We should use global keyword to create a global variable inside a function.


Example1

def myFunc():
    global x
    x = "A global variable"
    print(x)
myFunc()
print(x)

Output

A global variable
A global variable

Use the global keyword to make changes or to use a global variable inside a function.


Example2

x = "A global variable"
print(x)
def myFunc():
    global x
    x = "I m a variable"
    print(x)
myFunc()
print(x)

Output

A global variable
I m a variable
I m a variable