Learning objectives
By the end of this section you should be able to
- Identify the control flow of a program.
- Describe how control flow moves between statements and function calls.
Control flow and functions
Control flow is the sequence of program execution. A program's control flow begins at the main program but rarely follows a strict sequence. Ex: Control flow skips over lines when a conditional statement isn't executed.
When execution reaches a function call, control flow moves to where the function is defined and executes the function statements. Then, control flow moves back to where the function was called and continues the sequence.
Concepts in Practice
Following the control flow
Functions calling functions
Functions frequently call other functions to keep the modularity of each function performing one task. Ex: A function that calculates an order total may call a function that calculates sales tax. When a function called from another function finishes execution, control flow returns to the calling function.
Concepts in Practice
Functions calling functions
Consider the book club example above.
Try It
Updated terms and conditions prompt
Write an updated function, terms()
, that asks the user to accept the terms and conditions, reads in Y/N
, and outputs a response by calling accepted()
or rejected()
. accepted()
prints "Thank you for accepting the terms."
and rejected()
prints "You have rejected the terms. Thank you."
.
Given inputs 2
, "Y"
and "N"
, the output is:
Do you accept the terms and conditions? Y Thank you for accepting the terms.
Given a function call to terms()
and input "N"
, the output is:
Do you accept the terms and conditions? N You have rejected the terms. Thank you.
Try It
Laundromat information
Write a program that uses three functions to print information about a laundromat, Liam's Laundry:
laundromat_info()
: Prints the name, Liam's Laundry, and hours of operation, 7a - 11p, and callswashers_open()
anddryers_open()
washers_open()
: Reads an integer, assignswasher_count
with the value, and printswasher_count
dryers_open()
: Reads an integer, assignsdryer_count
with the value, and printsdryer_count
The main program should just call laundromat_info()
.
Given inputs 50
and 40
, the output is:
Liam's Laundry 7a - 11p Open washers: 50 Open dryers: 40