Skip to main content

Section 3.3 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 3.3.1

Given the following declarations:
alpha = 2
beta = 1
delta = 3
eta = 0
gamma = 0
omega = 2.5
theta = -1.3
kappa = 3.0
mu = 0.0
rho = 0.0
Evaluate these statements and determine the value of all variables used.
if alpha > delta:
    eta = alpha + 2
else:
    gamma = alpha + 5

Subsection 3.3.2 1. Diagram which statements go together by indentation

The first indented line (eta = alpha + 2) goes with the if statement, and the second indented line (gamma = alpha + 5) goes with the else statement.

Subsection 3.3.3 2. For conditional, determine whether expression is true

We evaluate alpha > delta, substituting 2 for alpha and 3 for delta.
2 > 3 is False.

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

The condition is False, so we execute the else branch.
gamma = alpha + 5
Substituting 2 for alpha, we evaluate the right-hand side to be 7 and store that in gamma. Therefore, the final value in the variables are:
  • alpha: 2
  • delta: 3
  • gamma: 7

Subsection 3.3.5 4. Repeat 2 and 3 as necessary

Repeating is not necessary in this case.
You have attempted of activities on this page.