Slide 1
Repetition Structures
Joan Boone
jpboone@email.unc.edu
Summer 2020
Repetition Structures Joan Boone jpboone@email.unc.edu Summer 2020 - - PowerPoint PPT Presentation
INLS 560 Programming for Information Professionals Repetition Structures Joan Boone jpboone@email.unc.edu Summer 2020 Slide 1 Topics Part 1 Basics while loops Part 2 for loops Part 3 Loop pattern: Using sentinels Loop
Slide 1
Joan Boone
jpboone@email.unc.edu
Summer 2020
Slide 2
Slide 3
– Decision structures choose among several possible
actions; also called conditional or branching structures
– Repetition structures repeat an action until some stop
condition is met; also called iteration or loop structures
Slide 4
amounts of data and produce summary results
– Google search results – Online banking reports – Directory and file listings on your computer – Data mining
same action on different data
generate a lot of code, is time-consuming, and error-prone
don't know how much data will be input to your program
Slide 5
condition is true
and exit the loop
number of times.
Slide 6
number < 10
True False
number = 0 print(number) number = number + 2
number = 0 while number < 10: print(number) number = number + 2 while condition: statement statement etc.
Slide 7
# A program to calculate sales commissions
# string variable to control the loop keep_going = 'yes' while keep_going == 'yes': sales = float(input('Enter the amount of sales: ')) commission_rate = float(input('Enter the commission rate: ')) commission = sales * commission_rate print('The commission is $', format(commission, ',.2f'), sep='') keep_going = input('Calculate another? ') Source: Starting Out with Python by Tony Gaddis Initialization Body of loop Controls loop entry and termination commission.py
Slide 8
Modify temp_conversion_v3.py to prompt for another temperature to convert while the user answers 'yes' to the 'Convert another?' prompt
# Convert a temperature value from Fahrenheit to Celsius, or vice versa temp = input('Enter a temperature value: ') if temp.isnumeric(): temp = float(temp) conversion = input('Enter type of conversion (f2c or c2f): ') if conversion == 'f2c': converted_temp = (temp - 32) * 5.0 / 9 print(temp, 'degrees Fahrenheit is ', converted_temp, ' degrees Celsius') else: if conversion == 'c2f': converted_temp = (temp * 9 / 5.0) + 32 print(temp, 'degrees Celsius is ', converted_temp, ' degrees Fahrenheit') else: print(conversion, 'is not a valid conversion type') else: print(temp, "is not a valid temperature value")
Enter a temperature value: 55 Enter type of conversion (f2c or c2f): f2c 55.0 degrees Fahrenheit is 12.78 degrees Celsius Convert another temperature? yes Enter a temperature value: 100 Enter type of conversion (f2c or c2f): c2f 100.0 degrees Celsius is 212.00 degrees Fahrenheit Convert another temperature? no
Sample inputs and
Slide 9
Problem: Given a negative bank balance, penalties, and deposits, how many weeks will it take to reach a positive balance? Algorithm: Each week, apply the penalty and deposit to the balance, until balance >= 0. Add a counter to keep track of the number of loop iterations. Answer: How many times does the loop iterate before balance >= 0 ?
# Calculates number of weeks to reach a positive balance balance = -200.00 # Starting balance penalty = 15.00 # Bank charges a penalty for negative balance deposit = 50.00 # Weekly deposit count = 0 while balance < 0: balance = balance - penalty balance = balance + deposit count = count + 1 print('Current balance: ', balance) print('Your balance will be positive in', count, 'weeks') negative_balance.py
Slide 10
# Calculates number of weeks to reach a positive balance balance = -200.00 # Starting balance penalty = 15.00 # Bank charges a penalty for negative balance deposit = 10.00 # Weekly deposit count = 0 while balance < 0: balance = balance - penalty balance = balance + deposit count = count + 1 print('Current balance: ', balance) print('Your balance will be positive in', count, 'weeks') negative_balance.py
Slide 11
Slide 12
for temp_type in ['Celsius','Fahrenheit','Kelvin']: print(temp_type) for num in range(5): print(num) → 0 1 2 3 4 for num in range(1,5): print(num) → 1 2 3 4
Sequence of integers
Another way to specify a sequence is to use the built-in function, range. This function creates a sequence of values that can be iterated over.
for num in [0,1,2,3,4]: print(num) → 0 1 2 3 4
number of times.
When the for loop executes, it iterates once for each item in the sequence.
→ Celsius Fahrenheit Kelvin
Sequence
for_loop_examples.py
Slide 13
# This program uses a loop to display a table # showing the numbers 1 through 10 and their squares. # Print the table headings. print('Number', '\t', 'Square') print('--------------') # Print the numbers 1 through 10 # and their squares. for number in range(1, 11): square = number**2 print(number, '\t\t', square)
Number Square
1 2 4 3 9 4 16 5 25 6 36 7 49 8 64 9 81 10 100
Source: Starting Out with Python by Tony Gaddis
Output
squares.py
Slide 14
# This program converts kph speeds to mph start_speed = 60 end_speed = 131 increment = 10 conversion_factor = 0.6214 print('KPH', '\t', 'MPH') print('-------------') for kph in range(start_speed, end_speed, increment): mph = kph * conversion_factor print(format(kph, '3d'), '\t', format(mph, '.1f'))
Initialization Body of loop Controls loop entry and termination
Source: Starting Out with Python by Tony Gaddis
speed_converter.py
Slide 15
# This program converts kph speeds to mph start_speed = 60 end_speed = 131 increment = 10 conversion_factor = 0.6214 print('KPH', '\t', 'MPH') print('-------------') for kph in range(start_speed, end_speed, increment): mph = kph * conversion_factor print(format(kph,'3d'), '\t', format(mph, '.1f')) KPH MPH
37.3 70 43.5 80 49.7 90 55.9 100 62.1 110 68.4 120 74.6 130 80.8
Source: Starting Out with Python by Tony Gaddis
Output
speed_converter.py
Python: Format Specification Mini-Language
Slide 16
start_speed = 60 end_speed = 131 increment = 10 conversion_factor = 0.6214 print('KPH', '\t', 'MPH') print('-------------')
for kph in range(start_speed, end_speed, increment):
mph = kph * conversion_factor print(format(kph,'3d'), '\t', format(mph, '.1f')) kph = 60 end_speed = 131 increment = 10 conversion_factor = 0.6214 print('KPH', '\t', 'MPH') print('-------------') while kph < end_speed: mph = kph * conversion_factor print(format(kph,'3d'), '\t', format(mph, '.1f')) kph = kph + increment speed_converter_while_loop.py
Slide 17
determine the number of weeks to reach a positive bank balance
Slide 18
max_numbers = 5 total = 0.0 print('This program calculates the sum of', max_numbers, 'numbers you will enter.') for counter in range(max_numbers): number = int(input('Enter a number: ')) total = total + number print('The total is', total) count = 0 while (balance < 0): balance = balance - penalty balance = balance + deposit count = count + 1 negative_balance.py: accumulates the number of weeks until balance is positive sum_numbers.py: sums/accumulates numbers entered by user
sum_numbers.py
Slide 19
# This program finds the running total for a sequence of numbers start = int(input('Enter starting number: ')) end = int(input('Enter ending number: ')) total = 0 for number in range(start, end + 1): total += number # same as: total = total + number print('Total=', total)
Operator Example Equivalent to += x += 5 x = x + 5
y -= 2 y = y - 2 *= z *= 10 z = z * 10 /= a /= b a = a / b %= c %= 3 c = c % 3 **= x **= 4 x = x**4
Slide 20
for each month of the year.
Enter rainfall in inches for month 1: 3.4 Enter rainfall in inches for month 2: 5.6 ... Enter rainfall in inches for month 12: 4.8 Total: 60.30 Average: 5.02 Initialize total rainfall counter For each month in a year Prompt user for inches of rainfall and convert to float Accumulate the total rainfall Calculate the average monthly rainfall Print the total rainfall and average monthly rainfall
Slide 21
Slide 22
Calculator: calculating squares, speed conversions for a set of values Accumulator: count loop iterations for bank balance, summing a sequence of numbers, calculating rainfall summaries Using sentinels allows the user to control the number of loops
Terminate when they enter a sentinel value to signal completion Input validation loop
processing
Nested loops
Slide 23
Pseudocode
Initialize a variable to the sentinel value
While the variable is equal to sentinel Get input data and process Get a new value for the sentinel
# A program to calculate sales commissions keep_going = 'yes' # a string variable to control the loop while keep_going == 'yes': sales = float(input('Enter the amount of sales: ')) commission_rate = float(input('Enter the commission rate: ')) commission = sales * commission_rate print('The commission is $', format(commission, ',.2f'), sep='') keep_going = input('Calculate another ? ')
Code
Source: Starting Out with Python by Tony Gaddis
A special value that signals when to end processing, and terminate the loop
commission.py
Slide 24
Pseudocode
Get the first input data
While the data is not equal to sentinel Get input data and process Get the new value for sentinel
# This program calculates property taxes tax_rate = 0.008377 # Tax rate for most of Orange County print('Enter property lot number, or 0 to end') lot = int(input('Lot number: ')) while lot != 0: value = float(input('Enter property value: ')) tax = value * tax_rate print('Property tax: $', format(tax, ',.2f'), sep='') print('Enter property lot number, or 0 to end') lot = int(input('Lot number: '))
Code
Source: Starting Out with Python by Tony Gaddis
property_tax.py
A special value that signals when to end processing, and terminate the loop
Slide 25
input to a program, to make sure it is valid before processing it.
as an input variable represents invalid data.
Prompt the user for the input value
While the value is not valid Display error message Prompt for the input value again Do something with the valid input value General algorithm
Slide 26
Prompt for temperature value
While temperature is invalid (value is not numeric) Display error message Prompt for temperature value again Convert temperature to float Prompt for conversion type While conversion type is invalid (value is not equal to 'f2c' or 'c2f') Display error message Prompt for conversion type again If converting Fahrenheit to Celsius Calculate the converted value and display result Else Calculate Celsius to Fahrenheit value and display result
Slide 27
temp = input('Enter a temperature value: ') # Validate user input for temperature value while not temp.isnumeric(): print('Error: temperature values must be numeric') temp = input('Enter a correct temperature value: ') temp = float(temp) conversion = input('Enter type of conversion (f2c or c2f): ') # Validate user input for conversion type value while conversion != 'f2c' and conversion != 'c2f': print('Error: conversion type must be f2c or c2f') conversion = input('Enter a correct conversion type: ') # Now that we know temp and conversion are valid values, do the conversion if conversion == 'f2c': converted_temp = (temp - 32) * 5.0 / 9 print(temp, 'degrees Fahrenheit is ', format(converted_temp, '.2f'), ' degrees Celsius') else: # conversion is c2f converted_temp = (temp * 9 / 5.0) + 32 print(temp, 'degrees Celsius is ', format(converted_temp, '.2f'), ' degrees Fahrenheit')
temp_conversion_input_validation.py
Slide 28
Slide 29
# This program counts through each second of 24 hours for hours in range(24): for minutes in range(60): for seconds in range(60): print(hours, ':', minutes, ':', seconds)
loop”)
iteration of its outer loop
– Innermost loop will iterate 60 times for each iteration of the middle loop – Middle loop will iterate 60 times for each iteration of the outermost loop
which iterates 24 times
Source: Starting Out with Python by Tony Gaddis
clock_simulator.py
Slide 30
– List and summarize credit card transactions by month (2 loops) – List all students in each class in each department (3 loops) – List schedule for each sport for each school in each NCAA
Division 1 conference (4 loops)
– Exam averager – Expense receipts – Temperature conversion input validation
Slide 31
and checks for the sentinel value (< 0) to terminate the loop
scores to enter
another_exam = True while another_exam: # Is there another set of exam scores to enter? number_of_scores = 0 total = 0.0 score = float(input('Enter exam score: ')) while score >= 0: total = total + score number_of_scores = number_of_scores + 1 score = float(input('Enter exam score: ')) if number_of_scores > 0: print('Average:', format(total / number_of_scores, '.2f')) else: print('No scores to average.') more_exams = input('Average another exam? ') if more_exams != 'yes': another_exam = False
nested_exam_average.py
Slide 32
monthly expense, and checks for the sentinel value (0) to terminate the loop
receipts to enter
# This program uses a nested loop to calculate monthly expenses number_of_months = 4 for month in range(number_of_months): total = 0.0 # initialize the total for each month more_receipts = True # initialize loop condition while more_receipts: print('Enter expense amount for month', month+1, '(0 when done)') expense = float(input('Amount: ')) if expense > 0: total = total + expense else: more_receipts = False print('Month ', month+1, ' total: $', format(total, '.2f'),sep='')
nested_expense_receipts.py