Skip to main content

Section 4.9 Sequential 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.9.1

Given the following declarations:
alpha = 2
beta = 1
delta = 3
eta = 0
gamma = 0
Evaluate these statements and determine the value of all variables used.
if alpha > beta:
    eta = alpha + 2
    gamma = alpha + 5
else:
    eta = alpha  - 1
    gamma = beta - 1
if alpha > delta:
    gamma = alpha + 5
else
    gamma = beta + 5
    eta = beta + 2;

Subsection 4.9.2 1: Diagram which statements go together by indentation.

Take note of the three parts of the sequence.
The first if-else (multiple lines) is highlighted in blue in the figure below.
The second if-else (single lines) is highlighted in yellow.
The final single statement is highlighted in green, and it is not part of the sequential if-else statements, so it will always be executed.
The figure shows the two if-else statements, each highlighted in a different color.
Figure 4.9.1.

Subsection 4.9.3 SG2: For conditional, determine whether expression is true

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 alpha > beta:
2 > 1 is True

Subsection 4.9.4 3. If true, follow true branch; If false, follow next elif/else branch or exit conditional if no else branch

eta = alpha + 2 = 2 + 2 = 4
gamma = alpha + 5 = 2 + 5 = 7
The figure shows the first if-else statements, highlighted in green.
Figure 4.9.2.

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

Because there are 2 sequential if-statements, we need to repeat SG2 and SG3 for the second if-statement in the sequence.
First we evaluate (alpha > delta):
(2 > 3) is FALSE

Subsection 4.9.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.
gamma = beta + 5 = 1 + 5 = 6
Next sequential statement is always executed:
eta = beta + 2 = 1 + 2 = 3
Figure 4.9.3.
Answer.
alpha = 2, beta = 1, delta = 3, eta = 3, gamma = 6

Practice Pages.

You have attempted 1 of 1 activities on this page.