Functions II

Introduction to Nested Functions

Learn how to create and correctly call nested/inner functions.


We've already learnt that functions have their own scope, the local scope.

#### global scope #### ... def my_function(): #### local scope #### ...
Python

You can use the local scope to create variables that are accessible only within the function.

#### global scope #### ... def my_function(): #### local scope #### local_var = 10
Python

This is not limited to just variables.

You can also create another function inside your function.

In this example, we create a function called inner that is nested inside a function called outer:

def outer(): #### nested function #### def inner(): print('hi')
Python

When using nested functions, the same rules for global and local scope apply.

Since inner is defined inside the local scope of outer, it cannot be called from outside of outer. If we try to do so, we will encounter an error:

def outer(): #### nested function #### def inner(): print('hi') inner()
Python
Output

To execute a nested function, you must call it from within the outer function. After that, you call the outer function to run everything:

def outer(): #### nested function #### def inner(): print('hi') inner() outer()
Python
Output

What will be the output?

def outer(): def inner(): print('Hello World') outer()
Python

What will be the output?

def outer(): def inner(): print('Hello World') inner()
Python

What will be the output?

def outer(): def inner(): print('Hello World') inner() outer()
Python

Remember that you can use the global keyword to declare a variable as global within a local scope:

def my_function(): global my_var my_var = 10
Python

This is only limited to variables and does not work for nested functions. Let's see what happens if we try:

def outer(): global inner def inner(): print('hi') inner()
Python
Output