Story – Python Scope

Alex was on his journey to become a master Python programmer. He had learned a lot about Python data types, control structures, functions, and object-oriented programming. But there was still one topic he had yet to fully understand: scope.

Scope refers to the visibility of variables in different parts of a program. In Python, there are three types of scopes: local, global, and nonlocal. Local variables are defined inside a function and can only be accessed within that function. Global variables are defined outside of a function and can be accessed from anywhere in the program. Nonlocal variables are used in nested functions and refer to variables defined in the outer function.

To better understand scope, Alex started by experimenting with local variables. He defined a function that created a local variable and then tried to access that variable outside of the function.

def my_function():
    x = 10

my_function()
print(x)

The code produced an error because x was not defined outside the function.

NameError: name 'x' is not defined

Next, Alex tried defining a global variable and accessing it from within a function.

x = 10

def my_function():
    print(x)

my_function()

The output was:

10

Alex was able to see that global variables could be accessed from within a function.

Finally, Alex experimented with nonlocal variables. He defined an outer function that created a variable and an inner function that tried to access that variable.

def outer_function():
    x = 10

    def inner_function():
        print(x)

    inner_function()

outer_function()

The output was:

10

Alex was able to see that the inner function was able to access the variable defined in the outer function by using the nonlocal keyword.

He continued to experiment with scope, exploring different ways to define and use variables within different parts of his Python programs. He found that understanding scope was an important aspect of writing clean, efficient, and maintainable code.