Inner Functions
Introduction:
- In Python, you can define functions inside other functions. These are called inner functions.
- Inner functions can be useful for keeping code modular and organized.
Example:
- Let's define a function with two inner functions.
Python Program:
python
def function():
print('Inside function.')
def innerFunction1():
print('Inner function 1.')
def innerFunction2():
print('Inner function 2.')
innerFunction1()
innerFunction2()
function()
Output:
Inside function.
Inner function 1.
Inner function 2.
Explanation:
- We define a function named
function(). - Inside
function(), we define two inner functions:innerFunction1()andinnerFunction2(). - We call these inner functions within
function(). - Finally, we call
function().
Working of Inner Functions:
- Let's understand how the inner functions work using the above example:
- Define
function(). - Call
function(). - Execute
print('Inside function.'). - Define
innerFunction1(). - Define
innerFunction2(). - Call
innerFunction1()and executeprint('Inner function 1.'). - Call
innerFunction2()and executeprint('Inner function 2.').
- Define
Scope of Inner Functions:
- Inner functions are only visible inside the outer function in which they are defined. You cannot call them outside the outer function.
Example: Calling Inner Function from Outside:
- If you try to call an inner function from outside its scope, a
NameErrorwill be raised.
Python Program:
python
def function():
print('Inside function.')
def innerFunction1():
print('Inner function 1.')
def innerFunction2():
print('Inner function 2.')
innerFunction1()
innerFunction2()
innerFunction1() # This will raise an error
Output:
Traceback (most recent call last):
File "example.py", line 13, in <module>
innerFunction1()
NameError: name 'innerFunction1' is not defined
Exercises:
- Create a Function with Inner Function:
Write a function
outer()with two inner functionsinner1()andinner2(). Call both inner functions insideouter().pythondef outer(): def inner1(): print('This is inner function 1.') def inner2(): print('This is inner function 2.') inner1() inner2() outer()
- Return Inner Function:
Write a function
outer()that returns one of its inner functions based on an argument.pythondef outer(choice): def inner1(): return 'This is inner function 1.' def inner2(): return 'This is inner function 2.' if choice == 1: return inner1 else: return inner2 func = outer(1) print(func())
Summary:
- In this tutorial, we learned how to define inner functions and their scope in a Python program. Practice writing inner functions to understand how they can help keep your code organized and modular!