Skip to content

Scope

In one line

Scope is the region of code where a variable name is visible and accessible.

In simple words

Scope determines where a variable name can be accessed. Python has four scope levels, remembered by the LEGB rule:

  1. Local — variables defined inside a function. Only visible within that function.
  2. Enclosing — variables in the outer function, visible to nested functions (closures).
  3. Global — variables defined at module level. Visible throughout the module.
  4. Built-in — Python's built-in names like len, print, int. Always available.

Use global to modify a global variable from inside a function, and nonlocal to modify an enclosing variable. Without these, assigning inside a function creates a new local variable instead.

Example

python
x = 10  # global

def outer():
    y = 20  # enclosing

    def inner():
        z = 30  # local
        print(x, y, z)  # can see all three

    inner()

outer()

# global keyword
counter = 0
def increment():
    global counter
    counter += 1

Scope follows LEGB: Local, Enclosing, Global, Built-in. Use global/nonlocal to modify outer variables.

Common confusions

  • Confused with: namespace

    The difference: Scope is the region where names are visible. A namespace is the actual mapping from names to objects. Scope is about visibility; namespace is about the storage mechanism.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary