0% found this document useful (0 votes)
13 views29 pages

W6L2-ch04 Pr4.5-Pr4.6

Chapter 4 covers common loop algorithms and the for statement in programming. It details various loop types, including while loops and for loops, and provides examples for summing values, counting matches, and validating input. The chapter emphasizes the importance of proper initialization, condition testing, and updates to avoid common programming errors like off-by-one mistakes.

Uploaded by

s150207
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views29 pages

W6L2-ch04 Pr4.5-Pr4.6

Chapter 4 covers common loop algorithms and the for statement in programming. It details various loop types, including while loops and for loops, and provides examples for summing values, counting matches, and validating input. The chapter emphasizes the importance of proper initialization, condition testing, and updates to avoid common programming errors like off-by-one mistakes.

Uploaded by

s150207
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Chapter 4: Loops (4.

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:
")

print("There were", negatives,


"negative values.")

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

largest = int(input("Enter a value:


"))
inputStr = input("Enter a value: ")
while inputStr != "" :
value = int(inputStr)
if value > largest :
largest = value
inputStr = input("Enter a value:
")
05/09/2025 8
Minimum
• Get first input value
• This is the smallest 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 smallest if necessary

smallest = int(input("Enter a value:


"))
inputStr = input("Enter a value: ")
while inputStr != "" :
value = int(inputStr)
if value < smallest :
smallest = value
inputStr = input("Enter a value: ")

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

value = int(input("Enter a value: "))


inputStr = input("Enter a value: ")
while inputStr != "“ :
previous = value
value = int(inputStr)
if value == previous :
print("Duplicate input")
inputStr = input("Enter a value: ")

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

for i in range(1, 10) :


print(i)
for version

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

Enter number of years: 10


1 10500.00
2 11025.00
3 11576.25
4 12155.06
5 12762.82
6 13400.96
7 14071.00
8 14774.55
9 15513.28
10 16288.95

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.

int i = a for i in range(a, b)


while i < b : :
. . . . . .
i = i + 1

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.

i = a # For this version of the loop the ‘+1’


while i <= b : is
. . . # very noticeable!. You must specify an
i = i + 1 upper
# bound that is one more than the last
value
# to be included in the range.

for year in range(1, numYears + 1) :

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.

• A for loop can also be used as a count-controlled loop that iterates


over a range of integer values.

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

You might also like