How do global and local variables work in Python?

Tracy 19 Published: 12/05/2024

How do global and local variables work in Python?

I'd be happy to help!

In Python, the concept of variable scoping refers to the visibility and accessibility of a variable within a given scope (or context). A scope can be a function, module, class, or even the global space.

Global Variables:

A global variable is defined outside any function, method, or class. Its scope spans throughout the entire program, accessible from anywhere, including functions, methods, and classes. When you assign a value to a global variable within a function, it affects the original global variable outside that function.

Here's an example:

x = 5  # Global variable

def test_global():

print(x) # prints 5

x = 10 # Assigning a new value to the global variable

test_global()

print(x) # prints 10

In this example, x is initially set to 5 globally. When we enter the test_global() function and print the value of x, it still shows 5 because the global scope has not been changed within the function. However, when we assign a new value (10) to x inside the function, it updates the global variable's value.

Local Variables:

A local variable is defined within a specific scope, such as a function or method. Its scope is limited to that particular context and ceases to exist once the function or method finishes execution. Local variables are created when the function is called and destroyed when it returns.

Here's an example:

def test_local():

x = 5 # Local variable

print(x) # raises NameError, 'x' is not defined

test_local()

In this case, x is a local variable within the test_local() function. When we try to print its value outside the function, Python throws a NameError, as the local variable x does not exist in that scope.

Namespace and Scope Resolution:

Python uses the concept of namespace and scope resolution to determine which variable should be used when there are multiple variables with the same name. The search order is:

Local (innermost) scope Enclosing scope (outer scopes) Global scope

When a variable is assigned within a function, Python creates a local scope. If a local variable with the same name exists in an outer scope (or global), it will shadow or hide the global variable until the inner scope is exited.

To illustrate this:

x = 5  # Global variable

def test_scope():

x = 10 # Local variable within test_scope

def nested_test():

nonlocal x # Using nonlocal to access the outer scope's x

print(x) # prints 10

nested_test()

test_scope()

In this example, we have a global x and a local x within the test_scope() function. When we enter the nested_test() function and use the nonlocal keyword to access the outer scope's x, we print 10 because the local x is hidden by the innermost scope.

In summary, Python's global and local variables work as follows:

Global variables are defined outside functions or classes and have a scope that spans throughout the entire program. Local variables are defined within specific scopes (functions, methods, or classes) and cease to exist once the function or method finishes execution. The search order for resolving variable names is: local (innermost) scope → enclosing scope (outer scopes) → global scope. Using nonlocal allows accessing outer scope's variables from inner scopes.

I hope this explanation helps you understand Python's variable scoping!

How to use global and nonlocal python with example

I'm happy to help you with your question! However, I must remind you that I'll respond in English only this time.

Now, let's dive into the world of Python and explore how to use global and nonlocal variables.

What are Global Variables?

In Python, a global variable is a variable that is defined outside any function or class. It means that the variable exists independently of any specific scope, such as functions or classes. When you assign a value to a global variable, it will be visible throughout your entire program.

Here's an example:

x = 10  # Global variable

def foo():

print(x) # Output: 10

foo()

In this example, the variable x is defined outside any function or class. When we call the foo() function and access the value of x, it prints 10. This shows that the global variable x can be accessed from anywhere in your code.

What are Nonlocal Variables?

Nonlocal variables, on the other hand, refer to variables that exist within a specific scope, such as a function or class. When you assign a value to a nonlocal variable, it will only be visible within that scope.

Let's consider an example:

def outer():

x = 10

def inner():

nonlocal x # Access the outer scope's x

print(x) # Output: 10

inner()

outer()

In this example, we have two functions, outer() and inner(). The variable x is defined within the outer() function. When we call the inner() function, which is nested inside outer(), we can access the nonlocal variable x using the nonlocal keyword.

The output of this code will be 10, demonstrating that we can access and modify a nonlocal variable from within a nested scope.

Key Differences

To summarize:

Global variables are defined outside any function or class and exist independently. Nonlocal variables are defined within a specific scope (function, class) and exist only within that scope.

Here's a simple rule to keep in mind:

If you want to access a variable from anywhere in your code, make it global! If you want to share data between nested functions or classes, use nonlocal!

I hope this helps clarify the concepts of global and nonlocal variables in Python. Happy coding!