Skip to main content
Engineering LibreTexts

6.2: Control Flow

  • Page ID
    117557
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    \( \newcommand{\dsum}{\displaystyle\sum\limits} \)

    \( \newcommand{\dint}{\displaystyle\int\limits} \)

    \( \newcommand{\dlim}{\displaystyle\lim\limits} \)

    \( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)

    ( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)

    \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

    \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)

    \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

    \( \newcommand{\Span}{\mathrm{span}}\)

    \( \newcommand{\id}{\mathrm{id}}\)

    \( \newcommand{\Span}{\mathrm{span}}\)

    \( \newcommand{\kernel}{\mathrm{null}\,}\)

    \( \newcommand{\range}{\mathrm{range}\,}\)

    \( \newcommand{\RealPart}{\mathrm{Re}}\)

    \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

    \( \newcommand{\Argument}{\mathrm{Arg}}\)

    \( \newcommand{\norm}[1]{\| #1 \|}\)

    \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

    \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    \( \newcommand{\vectorA}[1]{\vec{#1}}      % arrow\)

    \( \newcommand{\vectorAt}[1]{\vec{\text{#1}}}      % arrow\)

    \( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vectorC}[1]{\textbf{#1}} \)

    \( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)

    \( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)

    \( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)

    \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \(\newcommand{\longvect}{\overrightarrow}\)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    \(\newcommand{\avec}{\mathbf a}\) \(\newcommand{\bvec}{\mathbf b}\) \(\newcommand{\cvec}{\mathbf c}\) \(\newcommand{\dvec}{\mathbf d}\) \(\newcommand{\dtil}{\widetilde{\mathbf d}}\) \(\newcommand{\evec}{\mathbf e}\) \(\newcommand{\fvec}{\mathbf f}\) \(\newcommand{\nvec}{\mathbf n}\) \(\newcommand{\pvec}{\mathbf p}\) \(\newcommand{\qvec}{\mathbf q}\) \(\newcommand{\svec}{\mathbf s}\) \(\newcommand{\tvec}{\mathbf t}\) \(\newcommand{\uvec}{\mathbf u}\) \(\newcommand{\vvec}{\mathbf v}\) \(\newcommand{\wvec}{\mathbf w}\) \(\newcommand{\xvec}{\mathbf x}\) \(\newcommand{\yvec}{\mathbf y}\) \(\newcommand{\zvec}{\mathbf z}\) \(\newcommand{\rvec}{\mathbf r}\) \(\newcommand{\mvec}{\mathbf m}\) \(\newcommand{\zerovec}{\mathbf 0}\) \(\newcommand{\onevec}{\mathbf 1}\) \(\newcommand{\real}{\mathbb R}\) \(\newcommand{\twovec}[2]{\left[\begin{array}{r}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\ctwovec}[2]{\left[\begin{array}{c}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\threevec}[3]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\cthreevec}[3]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\fourvec}[4]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\cfourvec}[4]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\fivevec}[5]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\cfivevec}[5]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\mattwo}[4]{\left[\begin{array}{rr}#1 \amp #2 \\ #3 \amp #4 \\ \end{array}\right]}\) \(\newcommand{\laspan}[1]{\text{Span}\{#1\}}\) \(\newcommand{\bcal}{\cal B}\) \(\newcommand{\ccal}{\cal C}\) \(\newcommand{\scal}{\cal S}\) \(\newcommand{\wcal}{\cal W}\) \(\newcommand{\ecal}{\cal E}\) \(\newcommand{\coords}[2]{\left\{#1\right\}_{#2}}\) \(\newcommand{\gray}[1]{\color{gray}{#1}}\) \(\newcommand{\lgray}[1]{\color{lightgray}{#1}}\) \(\newcommand{\rank}{\operatorname{rank}}\) \(\newcommand{\row}{\text{Row}}\) \(\newcommand{\col}{\text{Col}}\) \(\renewcommand{\row}{\text{Row}}\) \(\newcommand{\nul}{\text{Nul}}\) \(\newcommand{\var}{\text{Var}}\) \(\newcommand{\corr}{\text{corr}}\) \(\newcommand{\len}[1]{\left|#1\right|}\) \(\newcommand{\bbar}{\overline{\bvec}}\) \(\newcommand{\bhat}{\widehat{\bvec}}\) \(\newcommand{\bperp}{\bvec^\perp}\) \(\newcommand{\xhat}{\widehat{\xvec}}\) \(\newcommand{\vhat}{\widehat{\vvec}}\) \(\newcommand{\uhat}{\widehat{\uvec}}\) \(\newcommand{\what}{\widehat{\wvec}}\) \(\newcommand{\Sighat}{\widehat{\Sigma}}\) \(\newcommand{\lt}{<}\) \(\newcommand{\gt}{>}\) \(\newcommand{\amp}{&}\) \(\definecolor{fillinmathshade}{gray}{0.9}\)
    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.

    Checkpoint: Calling a brunch menu function
    Concepts in Practice \(\PageIndex{1}\): Following the control flow

    Which line is executed first?

    1

    def park_greet():

    2

    """Output greeting."""

    3

    print("Welcome. Open sunrise to sunset.")

    4
    5

    car_count = 1

    6

    park_greet()

    7

    if car_count > 50:

    8

    # Direct to extra parking lot

    1. 1
    2. 3
    3. 5
    Answer

    c. Line 5 is the start of the main program, which is not indented. park_greet() is called on line 6 and executed.

    Concepts in Practice \(\PageIndex{2}\): Following the control flow

    Control flow moves to line 9, and park_greet() is called. Which line does control flow move to next?

    1
    def extra_lot():
    2
    # Function definition
    3
     
    4
    def park_greet():
    5
    """Output greeting."""
    6
    print("Welcome. Open sunrise to sunset.")
    7
     
    8
    car_count = 1
    9
    park_greet()
    10
    if car_count > 50:
    11
    extra_lot()
    1. 1
    2. 4
    3. 10
    Answer

    b. Control flow moves to where park_greet() is defined, at line 4.

    Concepts in Practice \(\PageIndex{3}\): Following the control flow

    Control flow moves to line 12, and extra_lot() is called. Which line does control flow move to after line 3 is executed?

    1
    def extra_lot():
    2
    """Output extra parking lot info."""
    3
    print("Take the second right to park.")
    4
     
    5
    def park_greet():
    6
    """Output greeting."""
    7
    print("Welcome. Open sunrise to sunset.")
    8
     
    9
    car_count = 1
    10
    park_greet()
    11
    if car_count > 50:
    12
    extra_lot()
    1. 5
    2. 8
    3. 12
    Answer

    c. Control flow returns to the line that called the function. Line 12 contains the function call to extra_lot(), so control flow returns to line 12.

    Concepts in Practice \(\PageIndex{4}\): Following the control flow

    What is the output?

    def park_greet():
      """Output greeting."""
      print("Welcome to the park")
    print("Open sunrise to sunset")
    
    park_greet()
    
    1. Welcome to the park
    2. Welcome to the park
      Open sunrise to sunset
    3. Open sunrise to sunset
      Welcome to the park
    Answer

    c. The program has an indentation mistake. print("Open ...") is unindented, so the statement is not a part of park_greet() and is executed first. Then, park_greet() is called, and print("Welcome ...") is executed.

    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.

    Checkpoint: Example: Book club email messages
    Concepts in Practice \(\PageIndex{5}\): Functions calling functions

    Consider the book club example above. How many function calls occur during the execution of the program?

    1. 2
    2. 3
    3. 6
    Answer

    c. The for loop has three iterations. Each iteration calls print_book_club(), which calls print_conf(). So the program calls print_book_club() three times and print_conf() three times.

    Concepts in Practice \(\PageIndex{6}\): Functions calling functions

    Consider the book club example above. When line 3 is reached and executed, which line does control flow return to?

    1. 1
    2. 11
    3. 16
    Answer

    b. Control flow returns to line 11, which called print_conf(). Then print_book_club() finishes, and control flow returns to line 16, which called print_book_club().

    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.
    Interactive Code
    # Define accepted()
    
    # Define rejected()
    
    # Define terms()
    
    terms()
     
    Input

    Y
    N

    Answer

    def accepted():
    print("Thank you for accepting the terms.")

    def rejected():
    print("You have rejected the terms. Thank you.")

    def terms():
    print("Do you accept the terms and conditions?")
    response = input()
    if response == "Y":
    accepted()
    else:
    rejected()

    terms() # call to test functionality with 'Y'
    terms() # call to test functionality with 'N'

    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 calls washers_open() and dryers_open()
    • washers_open(): Reads an integer, assigns washer_count with the value, and prints washer_count
    • dryers_open(): Reads an integer, assigns dryer_count with the value, and prints dryer_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
    Interactive Code
     
     
    Input

    50
    40

    Answer

    def washers_open():
    washer_count = int(input())
    print(" Open washers:", washer_count)

    def dryers_open():
    dryer_count = int(input())
    print(" Open dryers:", dryer_count)

    def laundromat_info():
    print("Liam's Laundry")
    print("7a - 11p")
    washers_open()
    dryers_open()

    laundromat_info()


    This page titled 6.2: Control Flow is shared under a CC BY 4.0 license and was authored, remixed, and/or curated by OpenStax via source content that was edited to the style and standards of the LibreTexts platform.