Chapter 4 Functions

4.2 The Dynamic Execution Process of Function Calls

Function calls are not sequential control flow because the control flow leaves the main program for the execution of the function body, and then returns to the main program again after the execution of the function being called. The dynamic execution sequence of the code above can be written as:

(1) def g(): # statement 1; function definition
(2) print (‘Hello , world ’) # statement 2; evaluating g(), executing function body; the return value is None by default.
(3) a = None # statement 2; return value assignment
(4) print (a) # statement 3

A function that does not contain any return statements is also called a procedure: calling of the function performs some tasks, but does not evaluate to a return value. Correspondingly, a call to a procedure is typically used as a single-line expression (e.g. g() in a single line), but not as a part of other expressions or statements. The function g above is a procedure that performs the display of a string message. The built-in function reload is another example procedure.

When the expression f() + f() + 1 in the code above is evaluated, the function f() is called twice. Each time the function body is executed, the message ‘called’ is displayed. As a result, the message is displayed twice, as shown by the outputs.

A function body can contain calls to other functions, leading to more complex dynamic execution sequences. Nevertheless, the mechanism for each function call evaluation remains the same: the control flow leaves the current statement for an execution of the function being called, and then returns, with the return value as the value of the fuction call expression. For example:

The dynamic execution sequence of the code above is illustrated by the messages printed out. In particular, the function call f() is nested as a part of the function call g(), because it is invoked in the execution of the function body of g.

© Copyright 2024 GS Ng.

Next Section - 4.3 Input Arguments