Section 6.1 Write Loops
Subgoals for Writing a Loop.
-
Determine purpose of loop
- Pick a loop structure (while, for, do_while)
- Define and initialize variables
-
Determine termination condition
- Invert termination condition to continuation condition
-
Write the loop body
- Update Loop Control Variable to reach termination
Subsection 6.1.1
Problem: Write a loop that will prompt the user to continue to enter numbers until a sentinel value (
-1
) is entered, and then find the maximum value entered.Subsection 6.1.2 1. Determine purpose of loop to pick loop structure (for, while)
Generally, while loops are a good choice for sentinel loops, since you cannot know up front how many times the code will need to iterate.
Subsection 6.1.3 2. Define variables before loop that have dependencies within the loop
The user must input at least one number in order for us to find a maximum. The variable
user_input
will also be used as the loop control variable, so we must define it before the loop begins.user_input = int(input("Enter a value, enter -1 to end."))
The
maximum
value must be updated during the loop based on its previous value, and will be printed after the loop, so that variable will need to be initialized prior to the loop.maximum = user_input
Subsection 6.1.4 3. Based on loop structure
The terminiation condition for this loop is when the user’s inputted value is equal to the sentinel. We need to invert that condition to identify the continuation condition instead. That continuation condition must involve the loop control variable, which in this case will be
user_input
.while user_input != -1:
Subsection 6.1.5 4. Write loop body
First, we must check whether the latest
maximum
is greater than the user_input
; if so, we must update the maximum
. This check is unnecessary during the first iteration of the loop, but is critical on every subsequent iteration.while user_input != -1:
if user_input > maximum:
maximum = user_input
We then need to update the
user_input
loop control variable so that the loop has a chance to end at some point based on the user’s value.while user_input != -1:
if user_input > maximum:
maximum = user_input
user_input = int(input("Enter a value, enter -1 to end."))
Answer.
user_input = int(input("Enter a value, enter -1 to end."))
maximum = user_input
while user_input != -1:
if user_input > maximum:
maximum = user_input
user_input = int(input("Enter a value, enter -1 to end."))
print(maximum)
You have attempted of activities on this page.