Python Tutorials
Basic

Data Structure and Data Types

String

List

Tuple

Set

Dictionary

Functions / Methods

Advance

Exception Handling

Python Scope of Variables


Scope of Variables in Python

The scope of a variable refers to the region in which it is created.

Local Scope Variables

Variables created within a function belong to the local scope variables.

The local scope variables can only be used within function.

Example
def python_function():
    name = "John"
    print(name)

python_function()
'John'

The name variable inside the python_function() scope is the local scope.


Scope of Variable in Nested Function.

A function within a function is also called a nested function.

A variable created inside a function is also available in the nested function.

Example
def python_function():
    name = "John"
    def welcome_function():
      print(name)

    welcome_function()

python_function()
'John'

In the above example, the scope of the variable name is not available outside of a function but, it is available in the nested function (welcome_function()).


Global Scope Variables

Global variables are those variables that are created in the main body of the Python module file.

It is possible to access global variables from both local and global scopes.

Example
name = "John"

def python_function():
    print(name)

python_function()

print(name)
'John'
'John'

In a Python module file and outside of a python_function(), the name variable belongs to the global scope.


Same Variable Names in Global and Local Scope

A variable with the same name inside and outside of a function is treated as a separate variable in Python.

Example
name = "John"

def python_function():
    name = "Smith"
    print(name)

python_function()

print(name)
'Smith'
'John'

In the above example, you can see the name variables for local and global scope are different, so it printed the different string texts for the same variable name.


Global Keyword in Python

The global keyword makes the variable global.

If you want to convert variable local scope to global scope, then you can use global keyword.

Example
def python_function():
    global name
    name = "John"

python_function()

print(name)
'John'

Using the global keyword, we have converted the scope of the local variable to global. Now the local variable is accessible globally.


The global keyword can be used to change the value of a global variable within a function.

Example
name = "John"

def python_function():
    global name
    name = "Smith"

python_function()

print(name)
'Smith'

Here, you can see we used the global keyword to change the value of a global variable within a function.