< previous | Table of Contents | next > |
4.4 FLOW OF EXECUTION
Program execution in Python begins at the program's first statement and proceeds sequentially, one statement at a time, from top to bottom. However, function definitions within this flow do not disrupt the overall execution; they are skipped over until those functions are called.
A function call acts as a detour in the execution flow, directing it to the body of the called function. The program executes all statements within the function's body and returns to carry on from where it left off. This process can become nested when functions call other functions. After completing a function, execution resumes in the function that made the call, and this continues until the program ends and terminates. Below, we will look at a simple example where function calls are nested and what the execution flow looks like then.
# function that multiplies two numbers together def multiply(number1, number2): return number1 * number2 # function that adds two numbers together def add(number1, number2): return number1 + number2 # function that raises one number to the power of another def power_of(number1, number2): return number1 ** number2 print(multiply(power_of(2,5), add(10, 5)))
- The program starts when the functions are called in the print statement.
- The first detour is to the
power_of()
function within themultiply()
function where 2 is raised to the power of 5, returning 32 to the caller. - Next the second input to the multiply function is calculated where 10 and 15 are added. Then 15 is returned to the caller.
- Both of the values 32 and 15 are now the inputs for the multiply function.
- Lastly, the product of 32 and 15 is calculated and the result, 480, returned and then printed out to the screen.
KEY THINGS TO REMEMBER
- Python starts executing code from the top, processing one statement at a time in the order they appear, from top to bottom.
- As Python encounters function definitions during the initial pass, it skips over them (does not execute their contents) until these functions are explicitly called.
- A function call redirects the execution flow from the calling location to the function being called. The program executes all statements within the function's body.
- After a function has executed all its statements, the program flow returns to the point immediately after where the function was called, continuing the sequential execution.
SELF-CONTROL EXERCISES
< previous | Table of Contents | next > |