How Functions Work in Python

In the previous article, we discussed the applications/advantages of using Functions in Python, now we will examine how functions work in Python. Before we delve further let us look at an example program.

def func2( ):
    print("Inside fun2( )")
def fun1( ):
    print("Before fun2( )")
    fun2( )
    print("After fun2( )")

#Main Code
print("Before fun1( )")
fun1( )
print("After fun1( )")

What would the output of the above code look like?

Analyzing How Functions Work in Python

The program from earlier would result in the following output:

Before fun1():
print("After fun1()")

Let us see the logic behind why the program would result in this output, firstly the program has no output execution statement before the #Main Code section. Then the fun1( ) function is called, which leads to its execution along with the execution of the fun2( ) function which is nested within and called for between the two print statements in fun1( ).

But what is the internal working behind the program? Internally, our system maintains a function call stack. A stack is a container or collection that allows insertions or deletions from one end. We can consider it as a box that is closed at one end and open at the other end. So suppose something is inserted into the stack, it has to be removed from the same end. Practically this means that whatever was inserted into the stack, goes out first. When a function is called, its data is stored in the function call stack.

Once the function is executed, the program returns to the line where the function was called and proceeds to the rest of the program. Let us look at another program involving functions and try to guess the output:

def fun():

#Main Code
10 10
10 10

The program stores the fun() function in the call stack, when the function is called twice a new copy of the same function would be created along with a copy of the local variables.

In the next article, we will explore the purpose and usage of Default Arguments in Python.

1 thought on “How Functions Work in Python”

Leave a Comment