Sobes.tech
Junior — Middle

Can you describe how variable scope works in Python?

sobes.tech AI

Answer from AI

In Python, variable scopes define where exactly in the code a variable is accessible. The main scopes are:

  • Local: variables declared inside a function or method, accessible only within it.
  • Enclosing: if a function is nested inside another function, the inner function can see variables from the outer function.
  • Global: variables declared at the module (file) level, accessible throughout the module.
  • Built-in: names defined in Python's standard library.

When accessing a variable, Python searches in the order: local → enclosing → global → built-in.

Example:

def outer():
    x = 'outer'
    def inner():
        print(x)  # accessing variable from enclosing scope
    inner()

outer()

Here, inner sees the variable x from the outer function.