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
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.