w3resource

Python Exercise: Access a function inside a function


Write a Python program to access a function inside a function.

Sample Solution:

Python Code:

# Define a function named 'test' that takes a parameter 'a'
def test(a):
    # Define a nested function 'add' that takes a parameter 'b'
    def add(b):
        # Declare 'a' from the outer scope as nonlocal to modify its value
        nonlocal a
        
        # Increment the value of 'a' by 1
        a += 1
        
        # Return the sum of 'a' (modified by the nonlocal statement) and 'b'
        return a + b
    
    # Return the inner function 'add' and its scope is retained due to closure
    return add

# Call the 'test' function with an argument '4' and assign the returned function to 'func'
func = test(4)

# Call the function 'func' with argument '4' and print the result
print(func(4)) 

Sample Output:

9 

Explanation:

In the exercise above the code defines nested functions and the usage of the 'nonlocal' keyword. The function "test(a)" defines a nested function "add(b)" that takes an argument 'b'. Within "add(b)", the 'nonlocal' keyword is used to modify the variable 'a' from the outer scope. The outer function "test(a)" returns the inner function "add(b)", and this returned function is assigned to the variable 'func'. Finally, it calls the function 'func' with an argument '4' and prints the result. This involves modifying the nonlocal variable 'a' and performing addition with the argument passed to 'func'.

Flowchart:

Flowchart: Python exercises: Access a function inside a function.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to execute a string containing Python code.
Next: Write a Python program to detect the number of local variables declared in a function.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.