CHAPTER 4
Repetition
Structures
In this unit, we will cover the While
loop. In the next unit we cover For
loops.
Copyright 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Topics
Introduction to Repetition Structures
The while Loop: a ConditionControlled Loop
Calculating a Running Total
Input Validation Loops
Sentinals
Copyright 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Introduction to Repetition
Structures
Often have to 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
Includes condition-controlled loops and countcontrolled loops
Copyright 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The while Loop: a ConditionControlled 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
Copyright 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The while Loop: a ConditionControlled Loop (contd.)
Copyright 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The while Loop: a ConditionControlled Loop (contd.)
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
Copyright 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Copyright 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Code Examples
# This program calculates sales commissions.
# Create a variable to control the loop. - Note this variable is not Boolean
keep_going = 'y' # better style use Boolean, assign to true
# Calculate a series of commissions.
while keep_going == 'y':
#MUST change the value of keep_going inside the loop
# Get sales and commission rate - Note the indentation of next lines
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('The commission is $', \
format(commission, ',.2f'), sep='')
# See if the user wants to do another one.
keep_going = input('Do you want to calculate another' + \
'commission (Enter y for yes): ') #ensures a finite loop
Copyright 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Infinite Loops
Loops must contain within themselves
a way to terminate
To avoid this, make it a
Something inside a while loop general
mustrule to change
the while condition
eventually make the condition false
variable in the loop
code.
E.g. keep_going in the
previous example.
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
Copyright 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
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
Copyright 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Calculating a Running Total
(contd.)
Copyright 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Calculating a Running Total Code
while keep_going : #now we use a Boolean what must the initial value be?
number = int(input('Enter a number: '))
total = total + number # what should total be initialized to?
count = count +1 # this would be useful to get the average if needed
#code to set keep_going to false if user has no more entries
# Display the total of the numbers. - Note this is after the loop ends
print('The total is', total)
The book shows this code in a for-loop.
From the previous slide, can you see what the
logic is and complete the code shown? This is
for your own practice no need to post it.
Copyright 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Loops Best Practices
Initialize all variables that are changed
inside the loop: counters, running
totals, user-input, etc.
Ensure the while condition starts at
true otherwise loop will never execute
Ensure while condition uses a
variables that is CHANGED inside the
loop
Last one: Use Boolean variables instead of y,
n, or on, off cases. It make look longer in code
Ensure that no but
code
isefficient
placed
inside
it is more
speed and
space wise.
the loop if it is not needed e.g.
printing the final result.
Copyright 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
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
Copyright 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The Augmented Assignment
Operators (contd.)
You dont have to use these but you need to know
the syntax. Many programmers like it because it
resembles C++.
Copyright 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
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, or -1 when
expecting user to enter grades. Can you think of other
examples?
Copyright 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
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 programs such that
bad input is never accepted
Copyright 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Input Validation Loops
(contd.)
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 and
end the loop via its condition
Copyright 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Input Validation Loops
(contd.)
Copyright 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Input Validation Code
while score < 0 or score > 100:
print('ERROR: The score cannot be negative')
print('or greater than 100.')
score = int(input('Enter the correct score: '))
What should score be initialized to so that the while
condition starts at true?
Only downside to this loop is it forces the user to enter a
value within the range, even if they decided to quit the
program. You can add if statement to end the loop.
Copyright 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Summary
This chapter covered:
Repetition structures, including:
Condition-controlled loops
Infinite loops and how they can be avoided
Calculating a running total and augmented
assignment operators
Copyright 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley