Chapter 4: Repetition Structures

¡Supera tus tareas y exámenes ahora con Quizwiz!

Topics for Chapter 4

- Introduction to Repetition Structures - The while Loop: a Condition-Controlled Loop - The for Loop: a Count-Controlled Loop - Calculating a Running Total - Sentinels - Input Validation Loops - Nested Loops

The while Loop

A Condition-Controlled Loop. While the condition is true, the program does something. - Two parts: - Condition tested for true or false value. - Statements repeated as long as the condition is true. - In a flow chart, the line goes back to the previous part. - General format: while condition: statements Note: Observe Figure 4-1 The logic of a while Loop In order for a loop to stop executing, something has to happen inside of the loop to make the condition false.

The for Loop

A count-controlled loop that iterates a specific number of times. - Use a for statement to write count-controlled loop. - Designed to work with a sequence of data items. - General format: for variable in [val1, val2, etc]: - Target variable: the variable in which is the target of the assignment at the beginning of each iteration. Example: simple_loop1.py # This program demonstrates a simple for loop # that uses a list of numbers. print('I will display the numbers 1 through 5.') for num in [1, 2, 3, 4, 5]" print(num) >>> I will display the numbers 1 through 5. 1 2 3 4 5 Example: simple_loop2.py # This program also demonstrates a simple for # loop that uses a list of numbers. print('I will display the odd numbers 1 through 9.') for num in [1, 3, 5, 7, 9]: print(num) In examples 1 & 2, the target variable is num Example: simply_loop3.py # This program also demonstrates a simple for # loop that uses a list of strings. for name in ['Winken', 'Blinken', 'Nod']: print(name) In this example, the target variable is name Note: Observe Figure 4-4 The for Loop

Infinite Loop

A loop that does not have any way of stopping. - Repeats until the program is interrupted or terminated. - Occurs when the programmer forget to include stopping code in the loop. - This would happen in commission.py if keep_going was never updated after being set to 'y' initially. Example: infinite.py # This program demonstrates an infinite loop. # Create a variable to control the loop. keep__going = 'y' # Warning! Infinite Loop! while keep_going == 'y': # Get a salesperson's sales and commission rate. 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='') Unfortunately, because keep_going was never updated, the loop will just keep displaying the commission price over and over again.

Nested Loops

A loop that is contained inside of another loop. Ex. An analog clock works like a nested loop. - The hours hand moves one for every twelve movements of the minutes hand: for each iteration of the "hours," do twelve iterations of "minutes." - The seconds hand moves 60 times for each movement of the minutes hand: for each iteration of "minutes," do 60 iterations of "seconds." Note: Observe Figure 4-8 Flowchart for a clock simulator

Augmented Assignment Operators

A special set of operators designs for this type of job: In many assignments, the variable on the left side of the = operator also appears on the right side of the operators. Also known as "shorthand operators." Augmented Assignment Operators Table: 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

Sentinels

A special value that makes the end of a sequence of items. - When a program reaches a sentinel, it knows that the end of the sequence of items reached, and the loop terminates. - Must be distinctive enough so as not to be mistake for a regular value in the sequence. - Example: When reading an input file, an empty line can be used as a sentinel. Ex. property_tax.py # This program displays property taxes. TAX_FACTOR = 0.0065 # Represents the tax factor. # Get the first lot number. print('Enter the property lot number') print(' or enter 0 to end.') lot = int(input('Lot number: ')) # Continue processing as long as the user # does not enter lot number 0. while lot != 0: # Get the property value. value = float(input('Enter the property value: ')) # Calculate the property's tax. tax = value * TAX_FACTOR # Display the tax. print('Property tax: $', format(tax, ',.2f'), sep='') # Get the next lot number. print('Enter the next lot number or') print('enter 0 to end.') lot = int(input('Lot number: '))

Iterable

Contains a sequence of values that can be iterated over.

Input Validation

Inspecting input before it is processed by the program. - If the input is invalid, prompt the user to enter the correct data. - * Commonly accomplished using a while loop, which repeats as long as the input is bad. - If the input is bad, display an error message and receive another set of set. - If the input is good, continue to process the input. Ex. gross_pay.py Note: Enter 400 hrs. and 20 for the hourly rate. The program gives the employee 8,000 dollars. Probably not meant to happen... Bad input led to bad output. Ex. retail_no_validation.py # This program calculates retail prices. mark_up = 2.5 # The markup percentage. another = 'y' # Variable to control the loop. # Process one or more items. while another == 'y' or another == 'Y': # Get the item's wholesale cost. wholesale = float(input("Enter the item's " + \ " wholesale cost: ")) # Calculate the retail price. retail = wholesale * mark_up # Display the retail price. ... # Do this again? ... Ex. retail_with_validation.py # Same code as previous example, except inside the "while another == 'y' or another == 'Y'" loop: while wholesale < 0: print('ERROR: the cost cannot be negative.') wholesale = float(input('Enter the correct wholesale cost: ')) # Prevents the wholesale cost from being a negative number. A negative price doesn't exist... Note: Observe Figure 4-7 Logic containing an input validation loop

Repetition Structure

Makes the computer repeat included code as necessary. - Includes condition-controlled loops.

Introduction to Repetition Structures

Often, you have to write code that performs the same task multiple times. - ex. For a bank transaction, there will be multiple people throughout the day doing the same kind of transaction require the same steps (enter pin, select withdraw or deposit, etc.). - Disadvantages of duplicating code: - Makes the program large. - Time consuming - May need to be corrected in many places. Repetition structure...

Iteration

One execution of the body of a loop.

Calculating a Running Total

Program often need to calculate a total of a series of numbers. - These typically include two elements: 1. A loop that reads each number in a series. 2. An accumulator variable. - Known as a program that keeps a running total: it accumulates the total and reads it in a series. - At the end of the loop, the accumulator will reference the total. Ex. sum_numbers.py # This program calculates the sum of a series # of numbers entered by a user. max = 5 # The maximum number. Note: max is a python 'function'. # Initialize an accumulator variable. total = 0.0 # Explain what we are doing. print('This program calculates the sum of') print(max, ' numbers you will enter.') # Get the numbers and accumulate them. for counter in range(max): number = int(input('Enter a number: ')) total = total + number # Display the total of the numbers. print('The total is', total) Note: Observe Figure 4-6 Logic for calculating a running total

Letting the User Control Loop Iterations

Sometimes the programmer does not know exactly how many times the loop will execute. Can receive range inputs from the user, place them in variables, and call the range function in the for loop clause using these variables. - Be sure to consider the end cases: range does not include the endling limit, so you must need to put variable2 + 1 as the ending limit to be more accurate. Example: user_squares1.py ... # Get the ending limit. print('This program displays a list of numbers') print(' (starting at 1) and their squares.') end = int(input('How high should I go?')) ... # Print the numbers and their squares. for number in range(1, end + 1): square = number**2 print(number, '\t', square) Example: user_squares2.py # Get the starting value. ... start = int(input('Enter the starting number: ')) # Get the ending limit. end = int(input('How high should I go? ')) ... # Print the numbers and their squares. for number in range(start, end + 1): square = number**2 print(number, '\t', square)

Input Validation Loops

The computer cannot tell the difference between good data and bad data. - If the user provides bad input, the program will produce bad output. - GIGO: Garbage In, Garbage Out. - It is important to design a program such that bad input is never accepted. To ensure you get good input from the user, you use input validation.

Key Points About Nested Loops

The inner loop goes through all of its iterations for each iteration of the outer loop. Inner loops complete their iterations faster than the outer loops. The total number of iterations in a loop: ... = number_iterations_inner * number_iterations_outer

Using the Target Variable Inside the Loop

The purpose of a target variable is to reference each item in a sequence as the loop iterates. The target variable can be used in calculations or tasks in the body of the loop. - Example: Calculating the square root of each number in a range. Example: squares.py # This program uses a loop to display a # table showing the numbers 1 through 10 # and their squares. # Print the table headings. print('Number\tSquare') print('----------------') # Print the numbers 1 through 10 # and their squares. for number in range (1, 11): square = number**2 print(number, '\t', square) >>> Number Square --------------------- 1 1 2 4 3 9 4 16 5 25 6 36 7 49 8 64 9 81 10 100 Example: speed_converter.py # This program converts the speeds 60 kph # through 130 kph (in 10 kph increments). start_speed = 60 end_speed = 130 increment = 10 conversion_factor = 0.6214 # Print the table headings. print(KPH\tMPH') print('----------------') # Print the speeds. for kph in range (start_speed, end_speed, increment): mph = kph * conversion_factor print(kph, '\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

Generating an Iterable Sequence that Ranges from Highest to Lowest

The range function can be used to generate a sequence with numbers in descending order. - Make sure starting number is larger than the end limit, and the step value is negative. - Ex. range(10, 0, -1) - ...is equivalent to [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] Here is an example of a loop that prints the numbers 5 down to 1: for num in range(5, 0, -1): print(num) >>> 5 4 3 2 1

Using the range Function with the for Loop

The range function simplifies the process of writing a for loop. - range returns an iterable object. range characteristics: - One argument is used as an ending limit: range(5) is equivalent to [0, 1, 2, 3, 4]. It always starts at 0 with range. - Two arguments: starting value and ending limit - range(4, 7) is equivalent to [4, 5, 6] - Three arguments: third argument is a step (skip) value - range (1, 10, 2) is equivalent to [1, 3, 5, 7, 9] Example: simple_loop4.py # This program demonstrates how the range # function can be used with a for loop. # Print a message five times. for x in range(5): print('Hello world!') >>> Hello world! Hello world! Hello world! Hello world! Hello world!

Target Variable

The variable which is the target of the assignment at the beginning of each iteration.

Summary of Chapter 4

This chapter covered: - Repetition structures are used when code needs to be repeated. These structures include: - Condition-controlled loops (while loop). - Count-controlled loop (for loop). - Nested loops (while and/or for loops). - Infinite loops should be avoided in almost all cases. - range function is used in for loops. - Calculating a running total and augmented assignment operators are common when dealing with repetition structures. - Sentinel values can be used to terminate loops.

while loop is known as a _____ loop

pretest - The while loop tests the condition before performing an iteration. - Will never execute if condition is false to start with. - Requires performing some steps prior to the loop to make the condition true, but sometimes we don't want to execute the loop so the condition can be false in those cases. A while loop is typically used when you don't know the exact number of times you need to repeat. Example: commission.py # This program calculates sales commissions. # Create a variable to control the loop. keep_going = 'y' # Calculate a series of commissions. while keep_going == 'y': # Get a salesperson's sales and commission rate. 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): ') Example: temperature.py # This program assists a technician in the process # of checking a substance's temperature # Create a variable to represent the maximum # temperature. max_temp = 102.5 # Get the substance's temperature. temperature = float(input('Enter the substance's Celsius temperature: ')) # As long as necessary, instruct the user to # adjust the thermostat while temperature > max_temp: print('The temperature is too high.') print('Turn the thermostat down and wait') print(' 5 minutes. Then take the temperature') print(' again and enter it. ') temperature = float(input('Enter the new Celcius temperature: ')) # Remind the user to check the temperature again in 15 minutes. print('The temperature is acceptable.') print('Check it again in 15 minutes.') Note: Observe Figure 4-3 Flowchart for the program commission.py.


Conjuntos de estudio relacionados

UNIT 3 Chapter 19 Inflammation and the Immune Response

View Set

NSCC HMGT-2670 Front Office Procedures Final Ch 9-15

View Set

Section 17: AWS Elastic Beanstalk

View Set

Intermediate Accounting 3313 (Elsie Ameen) Ch. 4

View Set

Research Methods II - Chapter 7 Quiz

View Set