What is scope in Python?

Scope is the part of a program where a variable can be used. Python looks for a name in four places, in this order, which is called the LEGB rule.

ScopeMeaning
LocalNames created inside the current function
EnclosingNames in an outer function that wraps the current one
GlobalNames created at the top level of the file
Built-inNames Python already has, like len and print
x = "global"

def outer():
    x = "enclosing"

    def inner():
        x = "local"
        print(x)

    inner()
    print(x)

outer()
print(x)

Output:

Tutorials Class - Output Window

local
enclosing
global

Use the global keyword to change a global variable inside a function, and nonlocal for a variable of the outer function. See Scope of Variables in Python.


Learn more about the similar topics:
Tutorials
Python Functions
Python Built-in Functions
Scope of Variables in Python
Pass function as an argument in Python
Exercises & Assignments
Python calculator program using functions
Interview Questions & Answers
What is a docstring in Python?
What is scope in Python?
What are *args and **kwargs in Python?