Skip to content

Python nonlocal keyword (statement) | Example code

  • by

Python nonlocal keyword (statement) is used to work with variables inside nested functions. It gives access to variables inside the inner function to the outer function.

Python nonlocal variable example

A simple example code uses the nonlocal keyword to declare that the variable is not local.

def shopping_bill(promo=False):
    items_prices = [10, 5, 20, 2, 8]
    pct_off = 0

    def half_off():
        nonlocal pct_off
        pct_off = .50

    if promo:
        half_off()

    total = sum(items_prices) - (sum(items_prices) * pct_off)
    print(total)


shopping_bill(True)

Output:

Python nonlocal keyword

What does the Python nonlocal statement do?

Nonlocal variables are used in nested functions whose local scope is not defined. With this statement, variables can be neither in the local nor the global scope.

def outer_func():
    x = "local"

    def inner_func():
        nonlocal x
        x = "nonlocal"
        print("inner:", x)

    inner_func()
    print("outer:", x)


outer_func()

Output:

inner: nonlocal
outer: nonlocal

What is the difference between nonlocal variables and global variables?

Answer: Global statement permits modification of global variable in the local scope and nonlocal statement permits modification of enclosing scope variable in the local scope.

Names declared with nonlocal must pre-exist but global can be declared with new names

Do comment if you have any doubts or suggestions no this Python keyword tutorial.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *