×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

Python nonlocal Keyword

By IncludeHelp Last updated : December 07, 2024

Description and Usage

The nonlocal is a keyword (case-sensitive) in python, it is used when we work with the nested functions and we need to use a function which is declared in outer function, if we do the same, a variable will be created as local and we then we will not be able to work with a variable in inner function which is declared in outer function.

In such a case, we can define the variable (which is declared in outer function) as a nonlocal variable in inner function using nonlocal keyword.

Syntax

Syntax of nonlocal keyword:

nonlocal variable_name

Sample Input/Output

def outerfunc():
  a = 10    
  def innerfunc():
    # nonlocal binding
    nonlocal a
    a = 100
        
  # calling inner function
  innerfunc()
  # printing the value of a
  print("a : ", a)

Output:
a : 100

Example 1

Define two variables in outer function and make one variable as nonlocal in inner function.

# python code to demonstrate an example 
# of nonlocal keyword 

# nested functions
def outerfunc():
    a = 10
    b = 20
    
    def innerfunc():
    # nonlocal binding
    nonlocal a
    a = 100 # will update
    b = 200 # will not update, 
        # it will be considered as a local variable
    
    # calling inner function
    innerfunc()
    # printing the value of a and b
    print("a : ", a)
    print("b : ", b)
    
# main code
# calling the function i.e. outerfunc()
outerfunc()

Output

a :  100
b :  20

As you see in the output, a and b are the variables of outerfunc() and in the innerfunc() we are binding variable a as local, thus a will not be local here but, b will be considered as local variable for innerfunc() and if we change the value of b that will be considered a new assigned for local variable(for innerfunc()) b.

Example 2

def outer_function():
    count = 0  # Variable in the enclosing scope

    def inner_function():
        nonlocal count  # Declare 'count' as nonlocal
        count += 1  # Modify the enclosing variable
        print("Inner count:", count)

    inner_function()
    inner_function()
    print("Outer count:", count)

outer_function()

Output

Inner count: 1
Inner count: 2
Outer count: 2

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.