Search⌘ K

Inner Functions, Scope, and the LEGB Rule

Explore how to define and use inner functions in Python and understand the scope hierarchy using the LEGB rule. This lesson helps you grasp how variables are resolved in different scopes including local, enclosing, global, and built-in, enabling better control over function behavior and variable accessibility.

We'll cover the following...

Inner functions

An inner function is simply a function that is defined inside another function. The following program shows how to do this:

Python 3.8
# outer function
def display( ) :
a = 500
print ('Saving is the best thing...')
# inner function
def show( ) :
print ('Especially when your parents have done it for you!')
print(a)
show( )
display( )

In the code above, show() is the inner function defined inside display(). Therefore, it can only be called from within display(). In that ...