Python Chapter 04 While Loop Notes
Python Chapter 04 While Loop Notes
Repetition
Structures
In this unit, we will cover the While
loop. In the next unit we cover For
loops.
Topics
Introduction to Repetition Structures
The while Loop: a ConditionControlled Loop
Calculating a Running Total
Input Validation Loops
Sentinals
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
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
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
Summary
This chapter covered:
Repetition structures, including:
Condition-controlled loops