Zone Of Makos

Menu icon

Local Scope in Python

In Python, variables can have different levels of scope. A variable's scope determines where in the code the variable can be accessed. When a variable is defined inside a function, it is said to have local scope. This means that the variable can only be accessed from within the function where it is defined.

Here's an example:


def my_function():
    x = 10
    print("x inside function:", x)

my_function()

# This will result in a NameError because x is not defined outside the function
print("x outside function:", x)

In the above code, the variable x is defined inside the function my_function() . This means that x has local scope, and can only be accessed from within my_function() .

When we call my_function() , the output will be:


x inside function: 10

However, if we try to access x outside the function, we'll get a NameError because x is not defined in the global scope:


# This will result in a NameError because x is not defined outside the function
print("x outside function:", x)

When we try to access x outside the function, Python will look for a variable named x in the global scope. Since x is only defined inside the function, Python can't find it and raises a NameError .

It's important to note that variables with local scope are created each time the function is called, and are destroyed when the function returns. This means that local variables are not persistent, and their values are not saved between function calls.

Understanding scope is an important concept in Python programming, and can help you write more organized, modular, and efficient code.