Friday, July 3, 2020

Flow of execution in a function call - python

Flow of execution in a function call:

    To understand the program execution we have to know  how a program is organized in the 
computer's primary memory(RAM). Below is a diagram given of a over simplified memory layout diagram


Heap
Dynamic memory allocation
Stack
Function call and local variable
Static/Global 
Stores Global Variable
Source Code
Stores the program instruction
Operating System
Stores the OS codes

This diagram will be used in our further discussion

    As we know that any function in order to work, has to be called with proper arguments. 
So we are going to look into how a function works, starting from the function call till result generation.  
We will consider a very simple addition program that adds two numbers.

def ad(a,b):
    return a+b

print(ad(10,30))

The above code takes 5 steps to be executed. Underneath we have listed the steps


Visualization
The now flow of execution is from top to bottom, line 1 gets executed but as it contains the def keyword 
and the interpreter gets aware that it is a function declaration, so it jumps over it. This shows that a function 
never gets executed unless called
The execution jumps to line 4, this is the point where the function ad is called inside the print function
 and an global frame is created that stores the function ad and its execution will start 
The execution control jumps to line 1 and the stack frame(memory block) for ad is created along with the
 values that are passed as arguments in the function call
Now the return statement is encountered in line 2
The sum operation is executed and the result is generated
Now the stack frame is destroyed and the value is returned to the calling function. Hence we get the output of 40

Points to remember:
1. Execution of a program starts from the first line of the code, executes one line at a time from top to bottom.
2.The function definition never changes the sequence of execution  of a program but the statements inside the function 
are only executed when the function is called.
3. A function can be called from inside of another function.
4. A function can be declared inside of another function declaration. 
5. This idea is similar to recursion.Don’t read the program from top to bottom but read the execution flow


References: 
2. Pythontutor
3. Computer Science with python Sumita arora
Share: