Digression: Scoring Matrices
Lecture 16
Indefinite Loops
L16 Indefinite Loops – 2
Objectives
• To understand the concepts of definite (for) and
indefinite (while) loops.
• To understand interactive loop and sentinel loop and
their implementations using a while statement.
• To be able to design and implement solutions to
problems involving loop patterns including nested loop
structures.
L16 Indefinite Loops – 3
for Loop: Revision
for i in range(10):
# do something
#—————————————————–
myList = [2,3,4,9,10]
for x in myList:
# iterates through the list elements
# do something that involves the list elements
#—————————————————–
myString = “hello there, hello world!”
for ch in myString:
# iterates through the string characters
#—————————————————–
infile = open(someFile, “r”)
for line in infile:
# iterate through the lines of the file
infile.close()
L16 Indefinite Loops – 4
Indefinite Loops
• Definite loops can be used only if we know the
number of iterations ahead of time, i.e. before
the loop starts.
• Sometimes, we don’t know how many iterations
we need until all the data has been entered.
• The indefinite or conditional loop keeps
iterating until certain conditions are met.
L16 Indefinite Loops – 5
Indefinite Loops
• while
•
statements. is a sequence of one or more
statements.
• Semantically, the body of the loop executes repeatedly
as long as the condition remains true.
• When the condition is false, the loop terminates.
L16 Indefinite Loops – 6
Indefinite Loops
• The condition is tested at the
top of the loop.
• This is known as a pre-test loop.
• If the condition is initially false,
the loop body will not execute at
all.
L16 Indefinite Loops – 7
Indefinite Loops
• Example of a while loop that counts from 0 to 9:
i = 0
while i < 10: # valid but poor use of while
print(i)
i += 1
• The code has the same output as this for loop:
for i in range(10) :# this is the right way
print(i)
• The while loop requires us to manage the loop variable i by
initializing it to 0 before the loop and incrementing it at the bottom of
the body.
• In the for loop this is handled automatically.
L16 Indefinite Loops - 8
Indefinite Loops
• The while statement is simple, but yet powerful and
dangerous – they are a common source of program
errors.
i = 0
while i < 10:
print(i)
• What happens with this code?
• The value of i never changes inside the loop body.
• This is an example of an infinite loop.
L16 Indefinite Loops - 9
Getting out of an Infinite Loop
• What should you do if you’re caught in an infinite loop?
– First, try pressing control-c (or STOP on Thonny)
– If that doesn’t work, try control-alt-delete
– If that doesn’t work, push the reset button!
www.forth.com
L16 Indefinite Loops - 10
Interactive Loops
• A good use of the indefinite loop is to write interactive
loops that allow a user to repeat certain portions of a
program on demand.
• Remember that we need to keep track of how many
numbers had been entered? Let’s use another
accumulator, called count.
• At each iteration of the loop, ask the user if there is
more data to process. We need to preset it to “yes” to go
through the loop the first time.
L16 Indefinite Loops - 11
Interactive Loops
# A program to average a set of numbers
# Illustrates interactive loop with two accumulators
def main():
moredata = "yes"
sum = 0.0
count = 0
while moredata[0].lower() == 'y':
x = float(input("Enter a number >> “))
sum += x
count += 1
moredata = input(“Do you have more numbers (yes or no)? “)
print(“\nThe average of the numbers is”, sum / count)
• Using string indexing (moredata[0]) allows us to accept
“y”, “yes”, “Y” to continue the loop
L16 Indefinite Loops – 12
Interactive Loops
Enter a number >> 32
Do you have more numbers (yes or no)? y
Enter a number >> 45
Do you have more numbers (yes or no)? yes
Enter a number >> 34
Do you have more numbers (yes or no)? yup
Enter a number >> 76
Do you have more numbers (yes or no)? y
Enter a number >> 45
Do you have more numbers (yes or no)? nah
The average of the numbers is 46.4
L16 Indefinite Loops – 13
Sentinel Loops
• A sentinel loop continues to process data until
reaching a special value that signals the end.
• This special value is called the sentinel.
• The sentinel must be distinguishable from the
data since it is not processed as part of the
data.
L16 Indefinite Loops – 14
Sentinel Loops
get the first data item
while item is not the sentinel
process the item
get the next data item
• The first item is retrieved before the loop starts. This is sometimes
called the priming read, since it gets the process started.
• If the first item is the sentinel, the loop terminates and no data is
processed.
• Otherwise, the item is processed and the next one is read.
• Assume we are averaging test scores. We can assume that there
will be no score below 0, so a negative number will be the sentinel.
L16 Indefinite Loops – 15
Sentinel Loops
# A program to average a set of numbers
# Illustrates sentinel loop using negative input as sentinel
def main():
sum = 0.0
count = 0
x = float(input(“Enter a number (negative to quit) >> “))
while x >= 0:
sum += x
count += 1
x = float(input(“Enter a number (negative to quit) >> “))
print(“\nThe average of the numbers is”, sum / count)
L16 Indefinite Loops – 16
Sentinel Loops
Enter a number (negative to quit) >> 32
Enter a number (negative to quit) >> 45
Enter a number (negative to quit) >> 34
Enter a number (negative to quit) >> 76
Enter a number (negative to quit) >> 45
Enter a number (negative to quit) >> -1
The average of the numbers is 46.4
L16 Indefinite Loops – 17
Sentinel Loops
• Now we can use of the interactive loop without the
hassle of typing ‘y’ all the time.
• BUT we can’t average a set of positive and negative
numbers.
• If we do this, our sentinel can no longer be a number.
• We could input all the information as strings.
• Valid input would be converted into numeric form.
Use a character-based sentinel.
• We could use the empty string (“”)!
L16 Indefinite Loops – 18
Sentinel Loops
initialize sum to 0.0
initialize count to 0
input data item as a string xStr
while xStr is not empty
convert xStr to a number x
add x to sum
add 1 to count
input next data item as a string xStr
Output sum / count
L16 Indefinite Loops – 19
Sentinel Loops
# A program to average a set of numbers
# Using empty string as loop sentinel
def main():
sum = 0.0
count = 0
xStr = input(“Enter a number (
while xStr != “”:
sum += float(xStr)
count += 1
xStr = input(“Enter a number (
print(“\nThe average of the numbers is”, sum / count)
L16 Indefinite Loops – 20
Sentinel Loops
Enter a number (
Enter a number (
Enter a number (
Enter a number (
Enter a number (
Enter a number (
Enter a number (
The average of the numbers is 3.38333333333
L16 Indefinite Loops – 21
Summary
• Indefinite loops
• Interactive loops
• Sentinel loops
Lecture 16�Indefinite Loops
Objectives
for Loop: Revision
Indefinite Loops
Indefinite Loops
Indefinite Loops
Indefinite Loops
Indefinite Loops
Getting out of an Infinite Loop
Interactive Loops
Interactive Loops
Interactive Loops
Sentinel Loops
Sentinel Loops
Sentinel Loops
Sentinel Loops
Sentinel Loops
Sentinel Loops
Sentinel Loops
Sentinel Loops
Summary