ST1- Week 4 Lecture
Repetition Structures
Topics
• Introduction to Repetition Structures
• The while Loop: a Condition-Controlled Loop
• The for Loop: a Count-Controlled Loop
• Calculating a Running Total
• Sentinels
• Input Validation Loops
• Nested Loops
• Using break, continue, and else with Loops
• Turtle Graphics: Using Loops to Draw Designs
Introduction to Repetition
Structures
• Often must write code that performs
the same task multiple times
• Disadvantages to duplicating code
• Makes program large
• Time consuming
• May need to be corrected in many places
• Repetition structure: makes computer
repeat included code as necessary
Condition-Controlled and
Count-Controlled Loops
• There are two broad categories of
loops:
• Condition-controlled
• uses a true/false condition to control the number of
times the loop iterates
• Count-controlled
• repeats a specific number of times
The while Loop: a Condition-
Controlled Loop
• while loop: while condition is true, do
something
• Two parts:
• Condition tested for true or false value
• Statements repeated as long as condition is true
• In flow chart, line goes back to previous part
• General format:
while condition:
statements
The while Loop: a Condition-
Controlled Loop (cont’d.)
The while Loop: a Condition-
Controlled Loop (cont’d.)
• In order for a loop to stop executing,
something has to happen inside the
loop to make the condition false
• Iteration: one execution of the body of
a loop
• while loop is known as a pretest loop
– Tests condition before performing an iteration
• Will never execute if condition is false to start with
• Requires performing some steps prior to the loop
Example: Computing Sales
Commission
Problem: Write a program that calculates
a 10 percent sales commission for
several salespeople.
'''
write a program that calculates a 10 percent sales commission
for several salespeople.
'''
# Create a variable to control the loop.
keep_going = 'y'
# Calculate a series of commissions.
while keep_going == 'y':
# Get a salesperson's sales and commission rate.
sales = float(input('Enter the amount of sales: '))
comm_rate = float(input('Enter the commission rate: '))
# Calculate the commission.
commission = sales * comm_rate
# Display the commission.
print(f'The commission is ${commission:,.2f}.')
# See if the user wants to do another one.
keep_going = input('Do you want to calculate another ' +
'commission (Enter y for yes): ')
Sentinels
• Sentinel: special value that marks the
end of a sequence of items
• When program reaches a sentinel, it knows
that the end of the sequence of items was
reached, and the loop terminates
• Must be distinctive enough so as not to be
mistaken for a regular value in the sequence
• Example: when reading an input file, empty
line can be used as a sentinel
Infinite Loops
• Loops must contain within themselves
a way to terminate
• Something inside a while loop must
eventually make the condition false
• Infinite loop: loop that does not have a
way of stopping
• Repeats until program is interrupted
• Occurs when programmer forgets to include
stopping code in the loop
Using the while Loop as a
Count-Controlled Loop
• The while loop is inherently a condition-controlled
loop
• It repeats as long as a Boolean condition is true
• However, you can use the while loop as a count-
controlled loop by pairing it with a counter variable
• A counter variable is assigned a unique value during
each iteration of a loop.
• It is called a counter variable because it can be used
to count the number of times the loop iterates
Using the while Loop as a
Count-Controlled Loop
• A count-controlled while loop must perform three
actions:
• Initialization: The counter variable must be initialized to a
suitable starting value before the loop begins.
• Comparison: The loop must compare the counter variable to a
suitable ending value, to determine whether the loop should
iterate or not.
• Update: During each iteration, the loop must update the counter
variable with a new value.
Using the while Loop as a
Count-Controlled Loop
• Example
n = 0 Initialization
while n < 5: Comparison
print(f'Inside the loop, the value of n is {n}.')
n += 1
Update
• Initialization: The variable n is initialized with 0
• Comparison: The loop iterates as long as n is less than 5
• Update: 1 is added to n
Single-Line while Loops
• If there is only one statement in the body of a while
loop, you can write the entire loop on one line.
• General format:
while condition: statement
•Example:
n = 0
while n < 10: n += 1
The for Loop: a Count-
Controlled Loop
• Count-Controlled loop: iterates a
specific number of times
• Use a for statement to write count-controlled
loop
• Designed to work with sequence of data items
– Iterates once for each item in the sequence
• General format:
for variable in [val1, val2, etc]:
statements
• Target variable: the variable which is the target of
the assignment at the beginning of each iteration
Using the range Function
with the for Loop
• The range function simplifies the
process of writing a for loop
• range returns an iterable object
• Iterable: contains a sequence of values that can be
iterated over
• range characteristics:
• One argument: used as ending limit
• Two arguments: starting value and ending
limit
• Three arguments: third argument is step value
Using the Target Variable
Inside the Loop
• Purpose of target variable is to
reference each item in a sequence as
the loop iterates
• Target variable can be used in
calculations or tasks in the body of the
loop
• Example: calculate square root of each
number in a range
# This program uses a loop to display a
# table showing the numbers 1 through 10
# and their squares.
# Print the table headings.
print('Number\tSquare')
print('--------------')
# Print the numbers 1 through 10
# and their squares.
for number in range(1, 11):
square = number**2
print(f'{number}\t{square}')
Letting the User Control the
Loop Iterations
• Sometimes the programmer does not
know exactly how many times the loop
will execute
• Can receive range inputs from the user,
place them in variables, and call the
range function in the for clause using
these variables
• Be sure to consider the end cases: range
does not include the ending limit
Generating an Iterable Sequence
that Ranges from Highest to Lowest
• The range function can be used to
generate a sequence with numbers in
descending order
• Make sure starting number is larger than end
limit, and step value is negative
• Example: range(10, 0, -1)
Calculating a Running Total
• Programs often need to calculate a
total of a series of numbers
• Typically include two elements:
• A loop that reads each number in series
• An accumulator variable
• Known as program that keeps a running total:
accumulates total and reads in series
• At end of loop, accumulator will reference the
total
Calculating a Running Total
(cont’d.)
# This program calculates the sum of a series
# of numbers entered by the user.
MAX = 5 # The maximum number
# Initialize an accumulator variable.
total = 0.0
# Explain what we are doing.
print('This program calculates the sum of ', end='')
print(f'{MAX} numbers you will enter.')
#By default there is a newline character appended to the item being printed
(end='\n'),
# and end='' is used to make it printed on the same line.
# Get the numbers and accumulate them.
for counter in range(MAX):
number = int(input('Enter a number: '))
total = total + number
# Display the total of the numbers.
print(f'The total is {total}.')
The Augmented Assignment
Operators
• In many assignment statements, the
variable on the left side of the =
operator also appears on the right side
of the = operator
• Augmented assignment operators:
special set of operators designed for
this type of job
• Shorthand operators
The Augmented Assignment
Operators (cont’d.)
Tax Calculator Example
• The ATO calculates the annual taxes on property using the following formula:
property tax = property value x 0.0065
• Every day, one of the tax office staff gets a list of properties for a council, and
has to calculate the tax for each property on the list for that council.
• You have been asked to design a program that the ATO staff can use to perform
these calculations.
• In your interview with the ATO staff member, you learn that each property in the
council is assigned a lot number, and all lot numbers are 1 or greater.
• You decide to write a loop that uses the number 0 as a sentinel value.
• During each loop iteration, the program will start by asking the ATO staff to
enter either a property’s lot number, or 0 to end.
# This program displays property taxes.
TAX_FACTOR = 0.0065 # Represents the tax factor.
# Get the first lot number.
print('Enter the property lot number or enter 0 to end.')
lot = int(input('Lot number: '))
# Continue processing as long as the user
# does not enter lot number 0.
while lot != 0:
# Get the property value.
value = float(input('Enter the property value: '))
# Calculate the property's tax.
tax = value * TAX_FACTOR
# Display the tax.
print(f'Property tax: ${tax:,.2f}')
# Get the next lot number.
print('Enter the next lot number or enter 0 to end.')
lot = int(input('Lot number: '))
Input Validation Loops
• Computer cannot tell the difference
between good data and bad data
• If user provides bad input, program will
produce bad output
• GIGO: garbage in, garbage out
• It is important to design program such that
bad input is never accepted
Input Validation Loops
(cont’d.)
• Input validation: inspecting input
before it is processed by the program
• If input is invalid, prompt user to enter correct
data
• Commonly accomplished using a while loop
which repeats as long as the input is bad
• If input is bad, display error message and receive
another set of data
• If input is good, continue to process the input
Input Validation Loops
(cont’d.)
Example: Retail Price Calculator (Writing
an Input Validation Loop)
Sam owns an import business, and she
calculates the retail prices of her
products, with a mark-up 2.5 times the
whole sale price. i.e.
retail price = wholesale cost x 2.5
# This program calculates retail prices.
MARK_UP = 2.5 # The markup percentage
another = 'y' # Variable to control the loop.
# Process one or more items.
while another == 'y' or another == 'Y':
# Get the item's wholesale cost.
wholesale = float(input("Enter the item's
wholesale cost: "))
# Calculate the retail price.
retail = wholesale * MARK_UP
# Display the retail price.
print(f'Retail price: ${retail:,.2f}')
# Do this again?
another = input('Do you have another item? ' +
'(Enter y or Y for yes): ')
# This program calculates retail prices.
MARK_UP = 2.5 # The markup percentage
another = 'y' # Variable to control the loop.
# Process one or more items.
while another == 'y' or another == 'Y':
# Get the item's wholesale cost.
wholesale = float(input("Enter the item's
wholesale cost: "))
# Validate the wholesale cost.
while wholesale < 0:
print('ERROR: the cost cannot be negative.')
wholesale = float(input('Enter the correct ' +
'wholesale cost: '))
# Calculate the retail price.
retail = wholesale * MARK_UP
# Display the retail price.
print(f'Retail price: ${retail:,.2f}')
# Do this again?
another = input('Do you have another item? ' +
'(Enter y for yes): ')
Nested Loops
• Nested loop: loop that is contained
inside another loop
• Example: analog clock works like a nested
loop
• Hours hand moves once for every twelve
movements of the minutes hand: for each iteration
of the “hours,” do twelve iterations of “minutes”
• Seconds hand moves 60 times for each movement
of the minutes hand: for each iteration of “minutes,”
do 60 iterations of “seconds”
Nested Loops (cont’d.)
• Key points about nested loops:
• Inner loop goes through all of its iterations for
each iteration of outer loop
• Inner loops complete their iterations faster
than outer loops
• Total number of iterations in nested loop:
number of iterations of inner loop X number of iterations of outer loop
Test scores calculator
• Kathryn, the science teacher in your school
wants you improve the program you have
written to get the average of each student’s
test scores.
• The program needs to ask the teacher/user
for the number of students first, and then ask
the teacher/user for number of test scores
for each student. Once these two inputs are
read, the average for each student needs to
be displayed.
# This program averages test scores. It asks the user for the
# number of students and the number of test scores per student.
# Get the number of students.
#num_students = int(input('How many students do you have? '))
while (num_students := int(input('How many students do you have?: '))) < 0:
print("Student numbers can't be negative")
# Get the number of test scores per student.
#num_test_scores = int(input('How many test scores per student? '))
while (num_test_scores := int(input('How many test scores per student?: '))) < 0:
print("Test scores can't be negative")
# Determine each students average test score.
for student in range(num_students):
# Initialize an accumulator for the test scores.
total = 0.0
# Display the student number.
print(f'Student number {student + 1}')
print('-----------------')
# Get the student's test scores.
for test_num in range(num_test_scores):
print(f'Test number {test_num + 1}', end='')
#score = float(input(': '))
while (score := float(input(': '))) < 0:
print("scores can't be negative")
# Add the score to the accumulator.
total += score
# Calculate the average test score for this student.
average = total / num_test_scores
# Display the average.
print(f'The average for student number {student + 1} '
f'is: {average:.1f}')
print()
Test Score Averages GUI
Input Validation Loops
(cont’d.)
• Using the walrus operator in an input
validation loop
• You can use the walrus operator to create an
assignment expression that combines the priming
read with the input validation loop
• Example:
while (score := int(input('Enter your score: '))) < 0:
print('The score cannot be negative.'
The break Statement
• The break statement causes a loop to
terminate
n = 0
while n < 100:
print(n)
if n == 5:
This statement causes the loop to stop
break
n += 1
print(f'The loop stopped and n is {n}.')
Program Output
0
1
2
3
4
5
The loop stopped and n is 5.
The continue Statement
• The continue statement causes the current
iteration of a loop to end early
• When the continue statement is executed,
all the statements in the body of the loop that
appear after it are ignored, and the loop
begins its next iteration (if there is a next
iteration)
The continue Statement
• Example:
n = 0
while n < 10:
n += 1
if n % 3 == 0:
continue This statement ends the current iteration and
print(n) causes the loop to skip to the next iteration.
Program Output
1
2
4
5
7
8
10
The else Clause with a Loop
• Loops in Python can have an optional else
clause.
while condition: for variable in [value1, value2, etc.]:
statement statement
statement statement
etc. etc.
else: else:
statement statement
statement statement
etc. etc.
The else Clause with a Loop
• An else clause in a loop is useful only when
the loop contains a break statement.
• The block of statements that appears after
the else clause executes only when the loop
terminates normally, without encountering a
break statement.
• If the loop terminates because of a break
statement, the else clause will not execute
its block of statements.
The else Clause with a Loop
• Example:
for n in range(10):
if n == 5:
print('Breaking out of the loop.')
break
print(n)
else:
print(f'After the loop, n is {n}.')
Program Output
0 The else clause did not execute
1
2
because the break statement
3 executed
4
Breaking out of the loop.
The else Clause with a Loop
• Example:
for n in range(3):
if n == 5:
print('Breaking out of the loop.')
break
print(n)
else:
print(f'After the loop, n is {n}.')
Program Output The break statement did not
0 execute, so the else clause
1
executed.
2
After the loop, n is 2.
Turtle Graphics: Using Loops
to Draw Designs
• You can use loops with the turtle to draw both
simple shapes and elaborate designs. For example,
the following for loop iterates four times to draw a
square that is 100 pixels wide:
for x in range(4):
turtle.forward(100)
turtle.right(90)
Turtle Graphics: Using Loops
to Draw Designs
• This for loop iterates eight times to draw the
octagon:
for x in range(8):
turtle.forward(100)
turtle.right(45)
Turtle Graphics: Using Loops
to Draw Designs
• You can create interesting designs by repeatedly
drawing a simple shape, with the turtle tilted at a
slightly different angle each time it draws the shape.
NUM_CIRCLES = 36 # Number of circles to draw
RADIUS = 100 # Radius of each circle
ANGLE = 10 # Angle to turn
for x in range(NUM_CIRCLES):
turtle.circle(RADIUS)
turtle.left(ANGLE)
Turtle Graphics: Using Loops
to Draw Designs
• This code draws a sequence of 36 straight
lines to make a "starburst" design.
START_X = -200 # Starting X coordinate
START_Y = 0 # Starting Y coordinate
NUM_LINES = 36 # Number of lines to draw
LINE_LENGTH = 400 # Length of each line
ANGLE = 170 # Angle to turn
turtle.hideturtle()
turtle.penup()
turtle.goto(START_X, START_Y)
turtle.pendown()
for x in range(NUM_LINES):
turtle.forward(LINE_LENGTH)
turtle.left(ANGLE)
Summary
• This topic covered:
• Repetition structures, including:
• Condition-controlled loops
• Count-controlled loops
• Nested loops
• Infinite loops and how they can be avoided
• range function as used in for loops
• Calculating a running total and augmented
assignment operators
• Use of sentinels to terminate loops
• Several Examples
• Using loops to draw turtle graphic designs