Skip to main content

Section 5.1 Write Conditional

Subgoals for writing conditionals:.

  1. Define how many mutually exclusive paths are needed
  2. Order paths from most restrictive to least restrictive
  3. Write conditional statement with Boolean expression
  4. Follow with true path including action in indentation
  5. Repeat 3 and 4 until all paths are included
  6. (Optional) Follow with else path including action in indentation

Subsection 5.1.1

Problem: Write the Python conditionals to solve the following specifications:
If integer variable current is odd, change its value so that it is now 4 times current plus 1; otherwise change its value so that it is now half of current (rounded down when current is odd).

Subsection 5.1.2 1. Define how many mutually exclusive paths are needed

In this case, the problem says to do one action if variable is odd, and a different action otherwise.
An integer can only be odd or even, so there are two mutually exclusive paths.

Subsection 5.1.3 2. Order paths from most restrictive to least restrictive

Since there are only two branches, the order does not matter.

Subsection 5.1.4 3. Write conditional statement with Boolean expression

To determine if the current variable is odd, we can check that the remainder (modulo) after dividing by 2 is one:
if current % 2 == 1:

Subsection 5.1.5 4. Follow with true path including action in indentation

In the True branch, we multiply the variable by 4 and add 1.
if current % 2 == 1:

Subsection 5.1.6 5. Repeat 3 and 4 until all paths are included

N/A since there is only the true and else path, which is below.

Subsection 5.1.7 6. (Optional) Follow with else path including action in indentation

In the else branch, we change the value to be half of its current value. We must make sure we keep the result as an integer, so we use integer division.
if current % 2 == 1:
    current = current * 4 + 1
else:
Answer.
if current % 2 == 1:
    current = current * 4 + 1
else:
    current //= 2
You have attempted of activities on this page.