Section 4.1 Write Conditional
Subgoals for writing conditionals:.
- Define how many mutually exclusive paths are needed
- Order paths from most restrictive to least restrictive
- Write conditional statement with Boolean expression
- Follow with true path including action in indentation
- Repeat 3 and 4 until all paths are included
- (Optional) Follow with else path including action in indentation
Subsection 4.1.1
Problem: Write the Python conditionals to solve the following specifications:
If integer variablecurrent
is odd, change its value so that it is now 4 timescurrent
plus 1; otherwise change its value so that it is now half ofcurrent
(rounded down whencurrent
is odd).
Subsection 4.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 4.1.3 2. Order paths from most restrictive to least restrictive
Since there are only two branches, the order does not matter.
Subsection 4.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 4.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:
current = current * 4 + 1
Subsection 4.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 4.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:
current //= 2
Answer.
if current % 2 == 1:
current = current * 4 + 1
else:
current //= 2
You have attempted of activities on this page.