Blog

Python Variables Scope

Python Variables Scope

python variables scope with legb rule mark as decorative image

Table of Contents

Python has three scopes of variables:
• Local scope
• Global scope
• Enclosing scope

LEGB rule

1. Local scope:

When a variable is declared within a function (see functions in Python), its scope is local. The variable is used within the function and exists only when the function is executed.

mark as decorative
note: A local variable is released from memory when the function call ends.

2. Global scope:

A global variable is declared outside all functions in the code file and has a scope that covers the entire code file.

Global scope mark as decorative

If a local variable is declared with the same name as a global variable within a function, the system will use the local variable.

mark as decorative
Note: Now, the `x` variable is mapped to the `x` variable outside the `f2()` function. When we change the value of `x`, the value of `x` outside the `f2()` function is also updated.

When we want to modify the value of a global variable within a function call, we use the `global` keyword before the variable:

x = 100 # global scope x

def myfunc():

    global x

    x = 200 print(x)

# x value is 200 inside myfunc myfunc()

print(x)

# x value is 200 outside myfunc

3. Enclosing function

# enclosing function
def f1():
    x = 42
    # nested function
    def f2():
        x = 0
        print(x) # x value is 0
    f2()
    print(x) # x value is still 42
f1()

The variable `x` does not change its value after calling the `f2()` function because the system initializes a new memory for the `x` variable inside the `f2()` function. To modify the value of `x` during the logical processing of the `f2()` function, we use the `nonlocal` keyword before the `x` variable:

# enclosing function
def f1():
     x = 42
    # nested function
    def f2():
        nonlocal x
        x = 0
        print(x) # x is now 0
    f2()
    print(x) # x value is now 0
f1()

Scoping Rule – LEGB Rule

Scoping Rule – LEGB Rule:
When a variable is referenced (used in some logic), Python follows the LEGB rule with the four levels of variable scope in order:
L – Local Scope
E – Enclosing scope (local variables in enclosing functions and lambdas)
G – Global Scope
B – Built-in variables available in Python.

Don’t forget to share this post!

Picture of Jack Nguyen
Jack Nguyen

The Tech-Savvy Solopreneur

Leave a Replay

Search

About Me

Jack Nguyen is a highly experienced business coach with a proven track record of helping entrepreneurs and small business owners achieve their goals.

Recent Posts
Follow Us
Weekly Tutorial
Play Video