repetition structures
play

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


  1. INLS 560 Programming for Information Professionals Repetition Structures Joan Boone jpboone@email.unc.edu Summer 2020 Slide 1

  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 2

  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 3

  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 4

  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 5

  6. while Loops General format: number = 0 while condition : statement statement etc. True print(number) number < 10 number = number + 2 Python example: False number = 0 while number < 10: print(number) number = number + 2 Slide 6

  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 Initialization # string variable to control the loop keep_going = 'yes' while keep_going == 'yes': Body of loop 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? ') Controls loop entry and termination Source: Starting Out with Python by Tony Gaddis commission.py Slide 7

  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") Sample Enter a temperature value: 55 inputs and Enter type of conversion (f2c or c2f): f2c 55.0 degrees Fahrenheit is 12.78 degrees Celsius outputs 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 Slide 8

  9. Using Loops to Count 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 9

  10. 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? # 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 10

  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 11

  12. for Loops ● 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. Sequence of integers for num in [0,1,2,3,4]: Sequence print(num) → 0 1 2 3 4 of strings for temp_type in ['Celsius','Fahrenheit','Kelvin']: → Celsius Fahrenheit Kelvin print(temp_type) 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 range(5): print(num) → 0 1 2 3 4 for num in range(1,5): print(num) → 1 2 3 4 for_loop_examples.py Slide 12

  13. for Loop: Calculating squares # 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') Output print('--------------') Number Square # Print the numbers 1 through 10 -------------- # and their squares. 1 1 for number in range(1, 11): 2 4 square = number**2 3 9 4 16 print(number, '\t\t', square) 5 25 6 36 7 49 8 64 9 81 10 100 squares.py Source: Starting Out with Python by Tony Gaddis Slide 13

  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 Initialization 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')) Controls loop entry and termination Body of loop Source: Starting Out with Python by Tony Gaddis speed_converter.py Slide 14

  15. for Loop: Converting a range of numbers # This program converts kph speeds to mph start_speed = 60 end_speed = 131 increment = 10 conversion_factor = 0.6214 print('KPH', '\t', 'MPH') print('-------------') Output for kph in range(start_speed, end_speed, increment): mph = kph * conversion_factor KPH MPH print(format(kph,'3d'), '\t', format(mph, '.1f')) ------------- 60 37.3 70 43.5 80 49.7 90 55.9 100 62.1 110 68.4 120 74.6 130 80.8 Python: Format Specification Mini-Language Source: Starting Out with Python by Tony Gaddis speed_converter.py Slide 15

  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 16

  17. Loop Patterns Repetition structures (loops) are used to solve many programming problems, and often follow one 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 17

  18. Loop pattern: Accumulator negative_balance.py: accumulates the number of weeks until balance is positive count = 0 while (balance < 0): balance = balance - penalty balance = balance + deposit count = count + 1 sum_numbers.py: sums/accumulates numbers entered by user 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) sum_numbers.py Slide 18

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend