Skip to main content
Engineering LibreTexts

4.5: Chained Decisions

  • Page ID
    117544
  • \( \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 branches taken in an if-elif and if-elif-else statement.
    • Create a chained decision statement to evaluate multiple conditions.

    elif

    Sometimes, a complicated decision is based on more than a single condition. Ex: A travel planning site reviews the layovers on an itinerary. If a layover is greater than 24 hours, the site should suggest accommodations. Else if the layover is less than one hour, the site should alert for a possible missed connection.

    Two separate if statements do not guarantee that only one branch is taken and might result in both branches being taken. Ex: The program below attempts to add a curve based on the input test score. If the input is 60, both if statements are incorrectly executed, and the resulting score is 75.

        score = int(input())
        if score < 70:
          score += 10
        # Wrong:
        if 70 <= score < 85:
          score += 5

    Chaining decision statements with elif allows the programmer to check for multiple conditions. An elif (short for else if) statement checks a condition when the prior decision statement's condition is false. An elif statement is part of a chain and must follow an if (or elif) statement.

    if-elif statement template:

        # Statements before
    
        if condition:
          # Body
        elif condition:
          # Body
        
        # Statements after
    Checkpoint: Example: Livestream features
    Concepts in Practice \(\PageIndex{1}\): Using elif

    Fill in the blank to execute Body 2 when condition_1 is false and condition_2 is true.

    if condition_1:
      # Body 1
    __ condition_2:
      # Body 2
    
    1. if
    2. elif
    3. else
    Answer

    b. elif will evaluate condition_2 if condition_1 is False and execute Body 2 if condition_2 is True .

    Concepts in Practice \(\PageIndex{2}\): Using elif

    Given x = 42 and y = 0, what is the final value of y?

    if x > 44:
      y += 2
    elif x < 50:
      y += 5
    
    1. 2
    2. 5
    3. 7
    Answer

    b. x > 44, 42 > 44, is False , so x < 50 is evaluated. 42 < 50 is True , so y = 0 + 5. Only one of the if and elif branches is taken.

    Concepts in Practice \(\PageIndex{3}\): Using elif

    Which conditions complete the code such that if x is less than 0, Body 1 executes, else if x equals 0, Body 2 executes.

    if _________:
      # Body 1
    elif _________:
      # Body 2
    
    1. x < 0
      x == 0
    2. x == 0
      x < 0
    3. x <= 0
      [no condition]
    Answer

    a. If x < 0, Body 1 executes. Else if x == 0, Body 2 executes.

    Concepts in Practice \(\PageIndex{4}\): Using elif

    Which of the following is a valid chained decision statement?

    1. if condition_1:
        # Body 1
      elif condition_2:
        # Body 2
      
    2. if condition_1:
        # Body 1
        elif condition_2:
          # Body 2
      
    3. elif condition_1:
        # Body 1
      if condition_2:
        # Body 2
    Answer

    a. The elif must be chained to a preceding statement and at the same indentation level.

    Concepts in Practice \(\PageIndex{5}\): Using elif

    Given attendees = 350, what is the final value of rooms?

    rooms = 1
    if attendees >= 100:
      rooms += 3
    if attendees <= 200:
      rooms += 7
    elif attendees <= 400:
      rooms += 14
    
    1. 4
    2. 15
    3. 18
    Answer

    c. The if and if-elif statements are not chained. The first if evaluates to True and executes. Then the if-elif is evaluated and the elif branch executes.

    if-elif-else statements

    Elifs can be chained with an if-else statement to create a more complex decision statement. Ex: A program shows possible chess moves depending on the piece type. If the piece is a pawn, show moving forward one (or two) places. Else if the piece is a bishop, show diagonal moves. Else if . . . (finish for the rest of the pieces).

    Checkpoint: Example: Possible chess moves
    Concepts in Practice \(\PageIndex{6}\): Using elif within if-elif-else statements

    Given hour = 12, what is printed?

    if hour < 8:
      print("Too early")
    elif hour < 12:
      print("Good morning")
    elif hour < 13:
      print("Lunchtime")
    elif hour < 17:
      print("Good afternoon")
    else:
      print("Too late")
    
    1. Good morning
    2. Lunchtime
    3. Good afternoon
    4. Too late
    Answer

    b. The third branch executes if hour < 8 and hour < 12 is False and hour < 13 is True .

    Concepts in Practice \(\PageIndex{7}\): Using elif within if-elif-else statements

    Where can an elif statement be added?

    _1_
    if condition:
      # Body
      _2_
    elif condition:
      # Body
    _3_
    else:
      # Body
    _4_
    
    1. 1
    2. 2
    3. 3
    4. 4
    Answer

    c. An elif can be chained to another elif to form a longer chained decision.

    Concepts in Practice \(\PageIndex{8}\): Using elif within if-elif-else statements

    Given x = -1 and y = -2, what is the final value of y?

    if x < 0 and y < 0:
      y = 10
    elif x < 0 and y > 0:
      y = 20
    else:
      y = 30
    
    1. 10
    2. 20
    3. 30
    Answer

    a. Only one branch is executed in a chained decision statement. -1 < 0 and -2 < 0 is True , so y = 10.

    Concepts in Practice \(\PageIndex{9}\): Using elif within if-elif-else statements

    How could the following statements be rewritten as a chained statement?

    if price < 9.99:
      order = 50
    if 9.99 <= price < 19.99:
      order = 30
    if price >= 19.99:
      order = 10
    
    1. if price < 9.99:
        order = 50
      else:
        order = 30
      order = 10
      
    2. if price < 9.99:
        order = 50
      elif price < 19.99:
        order = 30
      elif price == 19.99:
        order = 10
      
    3. if price < 9.99:
        order = 50
      elif price < 19.99:
        order = 30
      else:
        order = 10
    Answer

    c. The first branch executes if price < 9.99. The second branch executes if price < 19.99 and the first condition fails: that is, price >= 9.99. The third branch executes if the first and second conditions fail: that is, price >= 19.99. Chaining can simplify decision statements.

    Try It: Crochet hook size conversion

    Write a program that reads in a crochet hook's US size and computes the metric diameter in millimeters. (A subset of sizes is used.) If the input does not match B-G, the diameter should be assigned with -1.0. Ex: If the input is D, the output is "3.25 mm".

    Size conversions for US size: mm

    • B : 2.25
    • C : 2.75
    • D : 3.25
    • E : 3.5
    • F : 3.75
    • G : 4.0
    Interactive Code
    # Read in hook and compute diameter in mm 
    
    print(diameter, "mm")
     
    Input

    F

    Answer

    hook = input()
    diameter = 0

    if hook == "B":
    diameter = 2.25
    elif hook == "C":
    diameter = 2.75
    elif hook == "D":
    diameter = 3.25
    elif hook == "E":
    diameter = 3.5
    elif hook == "F":
    diameter = 3.75
    elif hook == "G":
    diameter = 4.0
    else:
    diameter = -1.0

    print(diameter, "mm")

    Try It: Color wavelengths

    Write a program that reads in an integer representing a visible light wavelength in nanometers. Print the corresponding color using the following inclusive ranges:

    • Violet: 380–449
    • Blue: 450–484
    • Cyan: 485–499
    • Green: 500–564
    • Yellow: 565–589
    • Orange: 590–624
    • Red: 625–750

    Assume the input is within the visible light spectrum, 380-750 inclusive.

    Given input:

        550

    The output is:

        Green
    Interactive Code
     
     
    Input

    550

    Answer

    color = int(input())

    if color < 450:
    print('Violet')
    elif color < 485:
    print('Blue')
    elif color < 500:
    print('Cyan')
    elif color < 565:
    print('Green')
    elif color < 590:
    print('Yellow')
    elif color < 625:
    print('Orange')
    else:
    print('Red')


    This page titled 4.5: Chained Decisions 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.