image
image
image

Python’s Global, Local and Nonlocal

image

Python’s Global Variables

Variables declared outside of a function in Python are known as global variables. They are declared in global scope. A global variable can be accessed outside or inside of the function.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

y= "global"

def foo():

print("y inside the function :", y)

foo()

print("y outside the function:", y)

Discussion

In the illustration above, y is a global variable and is defined a foo() to print the global variable y. When we call the foo() it will print the value of y.

Local Variables

A local variable is declared within the body of the function or in the local scope.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

def foo():

x = "local"

foo()

print(x)

Discussion

Running this program will generate an error indicating ‘x’ is undefined. The error is occurring because we are trying to access local variable x in a global scope whereas foo() functions only in the local scope.

Creating a Local Variable in Python

Example

A local variable is created by declaring a variable within the function.

def foo():

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

x = "local"

print(x)

foo()

Discussion

When we execute the code, the output is expected to be:

Local