Skip to main content

Section 4.13 Nested If/Else Statements

Subgoals for Evaluating Selection Statements.

  1. Diagram which statements go together by indentation
  2. For conditional, determine whether expression is true
    1. If true, follow true branch
    1. If false, follow next elif/else branch or exit conditional if no else branch
  3. Repeat step 2 as necessary

Subsection 4.13.1

You can watch this video or read through the content below it.
Given the following declarations:
alpha = 2
delta = 3
eta = 0
omega = 2.5
kappa = 3.0
Evaluate these statements and determine the value of all variables used.
if omega > kappa:
    if alpha < delta:
        eta = 5
    else:
        eta = 4
else:
    if alpha > delta:
        eta = 3
    else:
        eta = 2

Subsection 4.13.2 SG1: Diagram which statements go together.

In this diagram, the first thing to note is the parent/outer if-else statement highlighted in blue.
The true branch of the parent/outer statement contains an inner if-else.
Likewise, the else branch of the parent/outer statement contains an inner if-else.
Figure 4.13.1.

Subsection 4.13.3 SG2: For if statement, determine whether true or false

Because there are 2 sequential if-statements, we start with the first one, and then repeat SG2 and SG3 for the other.
First we evaluate (omega > kappa):
(2.5 > 3.0) is False

Subsection 4.13.4 SG3: If true, follow true branch. If false, follow else branch (OR do nothing if there is no else branch).

The else branch contains another if-else statement, so we must repeat the SG2 and SG3.
Figure 4.13.2.

Subsection 4.13.5 SG2: For if statement, determine whether true or false

Start with the first if-statement in the inner sequence.
First we evaluate (alpha > delta):
(2 > 3) is False

Subsection 4.13.6 SG3: If true, follow true branch. If false, follow else branch (OR do nothing if there is no else branch).

The condition is False so we follow the else branch.
eta = 2
Answer.
omega = 2.5, kappa = 3.0, alpha = 2, delta = 3, eta = 2

Subsection 4.13.7 Practice Pages

You have attempted 1 of 2 activities on this page.