How do I understand Python's variable scoping rules?

Understanding Python's variable scoping rules is crucial for writing clean and efficient code. Variable scope refers to the context in which a variable is defined and can be accessed. Python has four main scopes: local, enclosing, global, and built-in. If a variable is defined inside a function, it is considered local to that function. If it is declared outside any function, it is global. Enclosing scope refers to variables in nested functions. Built-in scope holds variables that Python defines by default.

Here's an example to illustrate Python's variable scoping:

def outer_function(): x = "outer x" def inner_function(): nonlocal x x = "inner x" print(x) inner_function() print(x) outer_function()

In this example, the variable x starts in the outer function's scope. The inner function modifies x using the nonlocal keyword, reflecting the change when it is printed from the outer function.


Python variable scoping local variables global variables enclosing variables built-in variables nonlocal keyword