W6L2-ch04 Pr4.5-Pr4.6
W6L2-ch04 Pr4.5-Pr4.6
5 –
4.6)
PART2: COMMON LOOP ALGORITHMS, THE
FOR STATEMENT
Chapter 3-Part2:
• Goals
• To become familiar with common loop algorithms
• Contents:
• Common Loop Algorithms
• The for loop
05/09/2025 2
Common Loop Algorithms
1. Sum and Average Value
2. Counting Matches
3. Prompting until a Match Is Found
4. Maximum and Minimum
5. Comparing Adjacent Values
05/09/2025 3
Average Example
Average of Values total = 0.0
• First total the values count = 0
• Initialize count to 0 inputStr = input("Enter value: ")
while inputStr != "" :
• Increment per input
value = float(inputStr)
• Check for count 0 total = total + value
• Before divide! count = count + 1
inputStr = input("Enter value:
")
if count > 0 :
average = total / count
else :
average = 0.0
05/09/2025 4
Sum Example
• Sum of Values
• Initialize total to 0
• Use while loop with sentinel
total = 0.0
inputStr = input("Enter value: ")
while inputStr != "" :
value = float(inputStr)
total = total + value
inputStr = input("Enter value: ")
05/09/2025 5
Counting Matches (e.g., Negative Numbers)
• Counting Matches negatives = 0
• Initialize negatives to 0 inputStr = input("Enter value: ")
• Use a while loop while inputStr != "“ :
value = int(inputStr)
• Add to negatives per
if value < 0 :
match
negatives = negatives + 1
inputStr = input("Enter value:
")
05/09/2025 6
Prompt Until a Match is
Found
• Initialize boolean flag to False
• Test sentinel in while loop
• Get input, and compare to range
• If input is in range, change flag to True
• Loop will stop executing
valid = False
while not valid :
value = int(input("Please enter a positive value < 100:
"))
if value > 0 and value < 100 :
valid = True
else :
print("Invalid input.")
This is an excellent way to validate provided inputs
Program will loop until a valid value is entered
05/09/2025 7
Maximum
• Get first input value
• By definition, this is the largest that you have seen so far
• Loop while you have a valid number (non-sentinel)
• Get another input value
• Compare new input to largest (or smallest)
• Update largest if necessary
05/09/2025 9
Comparing Adjacent Values
• Get first input value
• Use while to determine if there are more to check
• Copy input to previous variable
• Get next value into input variable
• Compare input to previous, and output if same
05/09/2025 10
Grades Example
• Examine the file: Grades.py
• Look carefully at the source code.
• The maximum possible score is read as user input
• There is a loop to validate the input
• The passing grade is computed as 60% of the available points
05/09/2025 11
Grades.py (1)
05/09/2025 12
Grades.py (2)
05/09/2025 13
Grades.py (3)
Program run:
05/09/2025 14
The for Loop
• Uses of a for loop:
• The for loop can be used to iterate over the contents of any
container.
• A container is is an object (Like a string) that contains or stores a
collection of elements
• A string is a container that stores the collection of characters in the
string
05/09/2025 15
An Example of a for Loop
• Notice the difference between the while loop and the for loop in the example.
• In the while loop, the index variable i is assigned 0, 1, and so on.
• In the for loop, the variable letter is assigned stateName[0], stateName[1],
and so on.
stateName = "Virginia"
i = 0
while i < len(stateName) :
letter = stateName[i]
print(letter) while version
i = i + 1
stateName = "Virginia"
for letter in stateName :
print(letter)
for version
05/09/2025 16
The for Loop (2)
• Uses of a for loop:
• A for loop can also be used as a count-controlled loop that iterates
over a range of integer values.
i = 1
while i < 10 :
while version
print(i)
i = i + 1
05/09/2025 17
Syntax of a for Statement
(Container)
• Using a for loop to iterate over the contents of a container, an element
at a time.
05/09/2025 18
Syntax of a for Statement
(Range)
• You can use a for loop as a count-controlled loop to iterate over a
range of integer values
• We use the range function for generating a sequence of integers that
less than the argument that can be used with the for loop
05/09/2025 19
Planning a for Loop
• Print the balance at the end of each year for a
number of years
05/09/2025 20
Good Examples of for Loops
• Keep the loops simple!
05/09/2025 21
Investment Example
05/09/2025 22
Programming Tip
• Finding the correct lower and upper bounds for a loop can be
confusing.
• Should you start at 0 or at 1?
• Should you use <= b or < b as a termination condition?
• Counting is easier for loops with asymmetric bounds.
• The following loops are executed b - a times.
05/09/2025 23
Programming Tip
• The loop with symmetric bounds (“<=”, is executed b - a + 1 times.
• That “+1” is the source of many programming errors.
05/09/2025 24
Steps to Writing a Loop
• Planning:
• Decide what work to do inside the loop
• Specify the loop condition
• Determine loop type
• Setup variables before the first loop
• Process results when the loop is finished
• Trace the loop with typical examples
• Coding:
• Implement the loop in Python
05/09/2025 25
A Special Form of the print Function
• Python provides a special form of the print function that does not start
a new line after the arguments are displayed
• This is used when we want to print items on the same line using
multiple print statements
• For example the two statements:
print(“00”, end=””)
print(3 + 4)
• Produce the output:
007
• Including end=“” as the last argument to the print function prints an
empty string after the arguments, instead on a new line
• The output of the next print function starts on the same line
05/09/2025 26
Summary of the for Loop
• for loops are very powerful
• The for loop can be used to iterate over the contents of any container,
which is an object that contains or stores a collection of elements
• a string is a container that stores the collection of characters in the string.
05/09/2025 27
Summary: Two Types of
Loops
• while Loops
• for Loops
• while loops are very commonly used (general purpose)
• Uses of the for loop:
• The for loop can be used to iterate over the contents of any
container.
• A for loop can also be used as a count-controlled loop that iterates
over a range of integer values.
05/09/2025 28
Summary
• Each loop requires the following steps:
• Initialization (setup variables to start looping)
• Condition (test if we should execute loop body)
• Update (change something each time through)
• A loop executes instructions repeatedly while a condition is True.
• An off-by-one error is a common error when programming loops.
• Think through simple test cases to avoid this type of error.
05/09/2025 29