Flow of function execution,uses,parameters & arguments
Flow of function execution
Flow of execution is order in which statements are executed in a script.
It is important to define a function before using the function.
Execution always begins from the first line of the program. Statements are executed one at a time, in order from top to bottom.
The interpreter finds main function and starts executing from there in sequence.
Statements inside function will be executed only if function is called. Function definition do not alter or change flow of execution.
The interpreter keeps a track and after completion of function the program resumes from where it left in the function that is called.
Uses of functions
Various reasons for using functions are:
It makes code easy to read and debug.
It allows us to name group of statements using that name we can call the function.
It makes code modules and increases modularity of code.
When required to update we can just change the module in one place.
It reduces chances of errors.
We can re-use the function in script.
Avoids repetition of code.
Parameters and Arguments
Whenever we define a function, its header consist of parentheses which may or may not contain parameter.
Parameter is defined by giving a name that appear in head of function or function definition and arguments are given while calling the function.
Parameter is present in method signature are called as formal parameters or formal argument and arguments passed in function call to invoke the defined function are called as actual parameters or actual argument.
Example of formal parameter and actual parameter
""" Author : ITVoyagers (itvoyagers.in)
Date :31st August 2020
Description : Program for showing formal parameters and actual parameters
Variables and Parameters are Local
Local variable is a variable present inside the function definition.
Parameters can be accessible only inside function and has no application outside function body.
Pass-by-value parameter passing
The value of the actual parameter is copied to the formal parameter. With pass-by-value, there is no way for the actual parameter to change value as the function gets its own copy.
In Python, scalar values are sent by-value. Lists and other objects are sent by reference.
op = add_me(b)
print ("Output is ", op)
print ("Output of b is ", b)
Output is 10
Output of b is 5
Pass-by-reference parameter passing
The reference to the actual parameter is sent to the function. When we execute a script, and a list is sent, we don’t copy the list to the actual parameter, we draw an arrow from formal to actual.