Skip to main content

Nested Functions

In Python, you can define functions inside other functions. These are known as nested or inner functions.

Scope of Variables

The scope of a variable refers to the region of a program where a variable is recognized and can be accessed. Python defines three main scopes inside functions:
  1. Local Scope: Variables created inside a function. They only exist while the function is running.
  2. Enclosing (Nonlocal) Scope: Variables in the outer function of a nested function.
  3. Global Scope: Variables defined at the top level of the file.

LEGB Rule

When you reference a variable name, Python searches for it in a strict order:
  • Local: First, it looks inside the current function.
  • Enclosing: Next, it looks at any outer (enclosing) functions.
  • Global: Then, it looks at variables defined at the top level of the script.
  • Built-in: Finally, it looks at Python’s pre-loaded built-in functions/constants (like len, print, None).
If the variable is not found in any scope, Python raises a NameError.

The global Keyword

If you want to modify a global variable from inside a function, you must declare it using the global keyword. Without it, Python creates a new local variable instead.
Precaution: Avoid overusing global variables. They make code harder to debug and maintain because any function can change them at any time.

The nonlocal Keyword

Similar to global, if you want to modify a variable in the enclosing (outer) function’s scope from inside an inner function, you must use the nonlocal keyword.
If you omit nonlocal message inside inner_function(), the change message = "Hello from Inner!" would only create a local variable named message inside the inner function, leaving the outer function’s variable unchanged.

What’s next?

Now that you know how variable scopes work, let’s look at Recursion — where a function calls itself to solve problems.

Recursion

Learn how functions call themselves