Repetition Structures Joan Boone jpboone@email.unc.edu Summer 2020 - - PowerPoint PPT Presentation

repetition structures
SMART_READER_LITE
LIVE PREVIEW

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
SLIDE 1

Slide 1

Repetition Structures

Joan Boone

jpboone@email.unc.edu

Summer 2020

INLS 560

Programming for Information Professionals

slide-2
SLIDE 2

Slide 2

Topics

Part 1

  • Basics
  • while loops

Part 2

  • for loops

Part 3

  • Loop pattern: Using sentinels
  • Loop pattern: Input validation

Part 4

  • Loop pattern: Nested loops
slide-3
SLIDE 3

Slide 3

Flow of Control

  • Flow of control is the order that a program performs

actions, or executes statements

  • Most programming languages use 2 kinds of

structures to control the flow of execution

– 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
SLIDE 4

Slide 4

Why Repetition?

  • Purpose of many software applications is to process large

amounts of data and produce summary results

– Google search results – Online banking reports – Directory and file listings on your computer – Data mining

  • Repetition structures are used when you need to repeat the

same action on different data

  • Writing the same code for different data is redundant, may

generate a lot of code, is time-consuming, and error-prone

  • You may not know how many times to repeat an action if you

don't know how much data will be input to your program

slide-5
SLIDE 5

Slide 5

2 Basic Types of Repetition Structures

while loop

  • Condition-controlled
  • Causes the statements in the loop to repeatedly execute as long as a

condition is true

  • Something has to happen inside the loop to make the condition false

and exit the loop

  • while loops repeat (execute or iterate) an indefinite number of times

for loop

  • Count-controlled
  • Causes the statements in the loop to repeatedly execute a specific

number of times.

  • for loops repeat (execute or iterate) a definite number of times
  • Can always be written as a while loop
slide-6
SLIDE 6

Slide 6

while Loops

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.

General format: Python example:

slide-7
SLIDE 7

Slide 7

while Loop Example

'User-controlled': the loop will continue to iterate as long as the user enters yes

# 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
SLIDE 8

Slide 8

Exercise: Add a loop to Temperature Conversion program to handle multiple conversions

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

  • utputs
slide-9
SLIDE 9

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

Using Loops to Count

slide-10
SLIDE 10

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

Exercise: Change the deposit amount to 10.00

  • What happens when you run the program again?
  • Why does this happen?
  • How do you fix it?
slide-11
SLIDE 11

Slide 11

Topics

Part 1

  • Basics
  • while loops

Part 2

  • for loops

Part 3

  • Loop pattern: Using sentinels
  • Loop pattern: Input validation

Part 4

  • Loop pattern: Nested loops
slide-12
SLIDE 12

Slide 12

for Loops

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

  • A for loop is a count-controlled loop that iterates a specific

number of times.

  • Loops are designed to work with a sequence of data items.

When the for loop executes, it iterates once for each item in the sequence.

→ Celsius Fahrenheit Kelvin

Sequence

  • f strings

for_loop_examples.py

slide-13
SLIDE 13

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

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

for Loop: Calculating squares

slide-14
SLIDE 14

Slide 14

for Loop: Converting a range of numbers

Using variables in the range function

# 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
SLIDE 15

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

  • 60

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

for Loop: Converting a range of numbers

slide-16
SLIDE 16

Slide 16

speed_converter: for-loop, while-loop

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
SLIDE 17

Slide 17

Loop Patterns

Repetition structures (loops) are used to solve many programming problems, and often follow

  • ne of several patterns.

Calculator pattern

  • Calculate the squares of a sequence of numbers
  • Convert a sequence of speeds from kph to mph

Accumulator pattern

  • Count number of times the loop is executed, e.g., to

determine the number of weeks to reach a positive bank balance

  • Sum a sequence of numbers
slide-18
SLIDE 18

Slide 18

Loop pattern: Accumulator

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
SLIDE 19

Slide 19

Using Augmented Assignment Operators

# 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
SLIDE 20

Slide 20

Exercise: Rainfall Summary

  • Write a program that prompts the user for the total rainfall in inches

for each month of the year.

  • Calculate the total annual rainfall, and the average monthly rainfall
  • Pseudocode
  • Sample input and output:

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 21

Slide 21

Topics

Part 1

  • Basics
  • while loops

Part 2

  • for loops

Part 3

  • Loop pattern: Using sentinels
  • Loop pattern: Input validation

Part 4

  • Loop pattern: Nested loops
slide-22
SLIDE 22

Slide 22

Loop Patterns

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

  • Example: Calculating sales commissions while keep_going == 'yes'
  • Continue looping as long as the user wants to enter input.

Terminate when they enter a sentinel value to signal completion Input validation loop

  • Continue to loop until the user enters valid input, then proceed with

processing

Nested loops

  • Loop within a loop within a loop …
slide-23
SLIDE 23

Slide 23

Loop Pattern: Using Sentinels

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
SLIDE 24

Slide 24

Loop Pattern: Using Sentinels

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
SLIDE 25

Slide 25

Loop Pattern: Input Validation

  • Input validation is the process of inspecting data that has been

input to a program, to make sure it is valid before processing it.

  • Input validation is commonly done with a loop that iterates as long

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
SLIDE 26

Slide 26

Input Validation for Temperature Conversion

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

Pseudocode

slide-27
SLIDE 27

Slide 27

Input Validation for Temperature Conversion

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')

Code

temp_conversion_input_validation.py

slide-28
SLIDE 28

Slide 28

Topics

Part 1

  • Basics
  • while loops

Part 2

  • for loops

Part 3

  • Loop pattern: Using sentinels
  • Loop pattern: Input validation

Part 4

  • Loop pattern: Nested loops
slide-29
SLIDE 29

Slide 29

Loop Pattern: Nested Loops

# 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)

  • A nested loop is one that is contained inside of another loop (“outer

loop”)

  • A nested loop (“inner loop”) executes all of its statements for every

iteration of its outer loop

  • In the example below there are 3 loops

– 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

  • The print statement will execute 86400 times (24 * 60 * 60)

Source: Starting Out with Python by Tony Gaddis

clock_simulator.py

slide-30
SLIDE 30

Slide 30

Nested Loop Scenarios

  • Scenarios

– 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)

  • while loops can contain for loops, and vice versa
  • Some examples (while loop contains while loop)

– Exam averager – Expense receipts – Temperature conversion input validation

slide-31
SLIDE 31

Slide 31

Nested Loop: Exam Score Average

  • Calculates the average of scores for multiple exams, using nested while loops
  • Outer while loop iterates until there are no more exams to average
  • Inner while loop prompts for the scores for a given exam, accumulates the total,

and checks for the sentinel value (< 0) to terminate the loop

  • Boolean variable, another_exam, indicates whether there is another set of exam

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
SLIDE 32

Slide 32

Nested Loop: Expense Receipts

  • Calculates total expenses for 4 months, using a while loop nested in a for loop
  • Outer for loop controls the number of months
  • Inner while loop controls accepting expense input, accumulating the total

monthly expense, and checks for the sentinel value (0) to terminate the loop

  • Uses a boolean variable, more_receipts, to indicate whether there are more

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