Lesson 9

Nested functions and nonlocal variables

Nested functions and nonlocal variables are concepts in Python that deal with the scope of variables when functions are defined within other functions. Understanding these concepts is essential for managing variable scope effectively and for creating more structured and modular code.


1. Nested Functions:

A nested function is a function defined inside another function. The inner function can access variables from the outer function's scope, but its own scope is local to the inner function.

def outer_function():
    outer_variable = "I'm from the outer function!"

    def inner_function():
        print(outer_variable)  # Accessing the outer function's variable

    inner_function()  # Calling the inner function

outer_function()  # Output: I'm from the outer function!

In this example:

  • inner_function() is nested inside outer_function().
  • inner_function() can access outer_variable, which is defined in outer_function(). 

Nonlocal variables

In some cases, you might want to modify a variable defined in the enclosing (outer) function from the inner function. To do this, you can use the nonlocal keyword. This keyword tells Python to look for the variable in the nearest enclosing scope that is not global.

def outer_function():
    count = 0  # Variable in the outer function

    def inner_function():
        nonlocal count  # Declare that we want to modify the outer variable
        count += 1
        print(count)

    inner_function()  # Output: 1
    inner_function()  # Output: 2

outer_function()

In this example:

  • count is defined in the outer_function().
  • inner_function() declares count as a nonlocal variable, allowing it to modify count in the outer function’s scope.
  • Each time inner_function() is called, it increments the count variable from the outer scope.


Summary

Nested functions and nonlocal variables provide a powerful way to structure your code and manage variable scope in Python. By using nested functions, you can encapsulate functionality and maintain access to variables in outer scopes. 

The nonlocal keyword enables modifications of these variables, facilitating state management in more complex function interactions. Understanding these concepts can help you write cleaner, more efficient, and modular code.
9
You've Completed Lesson 9

Next Up

10: Using return to get function results

Master the return statement in Python functions to output values, terminate execution, and return multiple values as tuples for modular coding.

Start Lesson 10