Python nonlocal keyword (statement) | Example code

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

Python nonlocal variable example

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:

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



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)

    print("outer:", x)



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 and suggestions no this Python keyword tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

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

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.