Chapter 4

Ace your homework & exams now with Quizwiz!

Repetition - While Loops

Use with a counter: x = 0 while x < 5: print(x) x += 1 Use with a sentinel value: x = True while x == True: v = input("T/F?") if v != "T": x = False

for loop to print messages

# Print a message five times. for x in range(5): print('Hello world') Hello world Hello world Hello world Hello world Hello world

for x in string: or in list

# Program to find the sum of all numbers stored in a list # List of numbers numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11] # variable to store the sum sum = 0 # iterate over the list for val in numbers: sum = sum+val print("The sum is", sum)

What will the following code display? total = 0 for count in range(1, 6): total = total + count print(total)

(6-1 = 5) so it will start at 1 and have five items in total so 1-5 1 0 + 1 = 1 : total = 1 2 1 + 2 = 3 : total = 3 3 3 + 3 = 6 : total = 6 4 6 + 4 = 10 : total = 10 5 10 + 5 = 15 : total = 15 it will print 15

The Augmented Assignment Operators

+=, -=, **=, /= and %= (i+= 8 is i = i + 8) used when assigning a new value to a variable based on its original value total = total + number balance = balance − withdrawal

How many times will 'Hello World' be printed in the following program? count = 10 while count < 1: print('Hello World')

0

4.9 What will the following code display? for number in range(6): print(number)

0 1 2 3 4 5 in this case u start at 0 and there's actually 6 items

4.11 What will the following code display? for number in range(0, 501, 100): print(number)

0 100 200 300 400 500 start at 0, finish at 500(501-1) increments of 100

for loop example

1 # This program demonstrates a simple for loop 2 # that uses a list of numbers. 3 4 print('I will display the numbers 1 through 5.') 5 for num in [1, 2, 3, 4, 5]: 6 print(num) I will display the numbers 1 through 5. 1 2 3 4 5

user inputted version

1 # This program displays a rectangular pattern 2 # of asterisks. 3 rows = int(input('How many rows? ')) 4 cols = int(input('How many columns? ')) 5 6 for r in range(rows): 7 for c in range(cols): 8 print('*', end='') 9 print()

* ** *** ****

1 # This program displays a triangle pattern. 2 BASE_SIZE = 8 3 4 for r in range(BASE_SIZE): 5 for c in range(r + 1): 6 print('*', end='') 7 print() As a result, the variable r is assigned the values 0 through 7 as the outer loop iterates. The inner loop's range expression, in line 5, is range(r + 1). The inner loop executes as follows: During the outer loop's first iteration, the variable r is assigned 0. The expression range(r + 1) causes the inner loop to iterate one time, printing one asterisk. During the outer loop's second iteration, the variable r is assigned The expression range(r + 1) causes the inner loop to iterate two times, printing two asterisks. During the outer loop's third iteration, the variable r is assigned The expression range(r + 1) causes the inner loop to iterate three times, printing three asterisks, and so forth.

num_list = [1, 2, 3] alpha_list = ['a', 'b', 'c'] for number in num_list: print(number) for letter in alpha_list: print(letter)

1 # first number in num_list a # first letter in aplha_list b # second letter in aplha_list c # third letter in aplha_list 2 # restart as for loop 2 is done a b c 3 a b c

4.12 What will the following code display? for number in range(10, 5, −1): print(number)

10 9 8 7 6 start at 10, finish at 6(5+1 since its (-1)), and goes backwards because c is -1

4.16 What will the following code display? number 1 = 10 number 2 = 5 number 1 = number 1 + number 2 print(number1) print(number2)

15 5

4.10 What will the following code display? for number in range(2, 6): print(number)

2 3 4 5 start at 2, finish at 5 because it's always one less than the b value

for loop

A count-controlled loop iterates a specific number of times. In Python, you use the for statement to write a count-controlled loop.

end=' '

A keyword parameter for the print() function that causes the function to NOT add a newline at the end of the string.

nested loop

A loop inside the body of another loop.

count-controlled loop

A loop that stops when a counter variable reaches a specified limit.

Calculating a Running Total

A running total is a sum of numbers that accumulates with each iteration of a loop. The variable used to keep the running total is called an accumulator.

Sentinels

A sentinel is a special value that marks the end of a sequence of values.

4.19 Why should you take care to choose a distinctive value as a sentinel?

A sentinel value must be unique enough that it will not be mistaken as a regular value in the list.

What is an accumulator?

A variable that is used to accumulate the total of a series of numbers

Write a while loop that asks the user to enter two numbers. The numbers should be added and the sum displayed. The loop should ask the user if he or she wishes to perform the operation again. If so, the loop should repeat, otherwise it should terminate.

CODE: calories=0 another = 'y' print('Find the total calories consumed forbreakfast and dinner.') while another =='y': breakfast= int(input('Enter total calories consumed for breakfast: ')) dinner=int(input('Enter total calories consumed for dinner: ')) calories= breakfast + dinner print('For both meals, the total calories consumed:',calories) another=input('Calculate another set of calories? Enter y for yes): ') print() PRINTS: Find the total calories consumed for breakfast and dinner. Enter total calories consumed for breakfast: 1500 Enter total calories consumed for dinner: 765 For both meals, the total calories consumed: 2265 Calculate another set of calories? Enter y for yes): y

It is not necessary to initialize accumulator variables.

False

The process of input validation works as follows: when the user of a program enters invalid data, the program should ask the user "Are you sure you meant to enter that?" If the user answers "yes," the program should accept the data.

False

To calculate the total number of iterations of a nested loop, add the number of iterations of all the loops.

False

step value

If you pass a third argument to the range function, that argument is used as step value. Instead of increasing by 1, each successive number in the sequence will increase by the step value. Here is an example: for num in range(1, 10, 2): print(num) 1 3 5 7 9 The first argument, 1, is the starting value for the sequence. The second argument, 10, is the ending limit of the list. This means that the last number in the sequence will be 9. The third argument, 2, is the step value. This means that 2 will be added to each successive number in the sequence.

target variable inside loop

In a for loop, the purpose of the target variable is to reference each item in a sequence of items as the loop iterates. In many situations it is helpful to use the target variable in a calculation or other task within the body of the loop. 1 # This program uses a loop to display a 2 # table showing the numbers 1 through 10 3 # and their squares. 4 5 # Print the table headings. 6 print('Number\tSquare') 7 print('--------------') 8 9 # Print the numbers 1 through 10 10 # and their squares. 11 for number in range(1, 11): 12 square = number**2 13 print(number, '\t', square)

4.23 What is a priming read? What is its purpose?

It is the input operation that takes place just before an input validation loop. The purpose of the priming read is to get the first input value.

accumulator for loop

MAX = 5 # The maximum number 5 total = 0 for counter in range(MAX): number = int(input('Enter a number: ')) 1 total = total + number

4.24 If the input that is read by the priming read is valid, how many times will the input validation loop iterate?

None

Patterns using nested loops

One interesting way to learn about nested loops is to use them to display patterns on the screen.

Review Questions

Review Questions

for x in range (a,b,c):

The first argument, a, is the starting value for the sequence. The second argument, b, is the ending limit of the list. This means that the last number in the sequence will be b. The third argument, c, is the step value. This means that c will be added to each successive number in the sequence. for num in range (1,10,2): print(num) 1 3 5 7 9

Describe the steps that are generally taken when an input validation loop is used to validate data.

The input is read, then a pretest loop is executed. If the input data is invalid, the body of the loop executes. In the body of the loop, an error message is displayed so the user will know that the input was invalid, and then the input read again. The loop repeats as long as the input is invalid.

range function

The set of all possible output values of a function range that simplifies the process of writing a count-controlled for loop. The range function creates a type of object known as an iterable.

Accumulator Variable

The variable that is used to accumulate It is often said that the loop keeps a running total because it accumulates the total as it reads each number in the series. Figure 4-6 shows the general logic of a loop that calculates a running total.

Garbage in-Garbage out

This term refers to the fact that computers will process nonsensical, faulty or incomplete input data and produce nonsensical, faulty or incomplete output. Enter the hours worked this week: 400 Enter the hourly pay rate: 20 The gross pay is $8,000.00 *allowed 400 hours to be inputted which is why input validation loops are used

# # # # # # First row: 0 spaces followed by a # Second row:1 space followed by a # Third row:2 spaces followed by a # Fourth row:3 spaces followed by a # Fifth row:4 spaces followed by a # Sixth row:5 spaces followed by a #

To display this pattern, we can write code containing a pair of nested loops that work in the following manner: The outer loop will iterate six times. Each iteration will perform the following: The inner loop will display the correct number of spaces, side by side. Then, a # character will be displayed. 1 # This program displays a stair-step pattern. 2 NUM_STEPS = 6 3 4 for r in range(NUM_STEPS): 5 for c in range(r): 6 print(' ', end='') 7 print('#') As a result, the outer loop iterates 6 times. As the outer loop iterates, variable r is assigned the values 0 through 5. The inner loop executes as follows: During the outer loop's first iteration, the variable r is assigned 0. A loop that is written as for c in range(0): iterates zero times, so the inner loop does not execute at this time. During the outer loop's second iteration, the variable r is assigned 1. A loop that is written as for c in range(1): iterates one time, so the inner loop iterates once, printing one space. During the outer loop's third iteration, the variable r is assigned 2. A loop that is written as for c in range(2): will iterate two times, so the inner loop iterates twice, printing two spaces, and so forth.

A condition-controlled loop always repeats a specific number of times.

True

In a nested loop, the inner loop goes through all of its iterations for every single iteration of the outer loop.

True

The following statement subtracts 1 from x: x = x − 1

True

The while loop is a pretest loop.

True

Give a general description of the input validation process.

When input is given to a program, it should be inspected before it is processed. If the input is invalid, then it should be discarded and the user should be prompted to enter the correct data.

Should an accumulator be initialized to any specific value? Why or why not?

Yes, it should be initialized with the value 0. This is because values are added to the accumulator by a loop. If the accumulator does not start at the value 0, it will not contain the correct total of the numbers that were added to it when the loop ends.

pretest loop

a loop whose condition is evaluated before the instructions in its loop body are processed. ex: While loop

while loop

a programming construct used to repeat a set of commands (loop) as long as (while) a boolean condition is true The loop has two parts: (1) a condition that is tested for a true or false value (2) a statement or set of statements that is repeated as long as the condition is true.

A(n) variable keeps a running total. sentinel sum total accumulator

accumulator

The -= operator is an example of a(n) operator. relational augmented assignment complex assignment reverse assignment

augmented assignment

Does the while loop test its condition before or after it performs an iteration

before

A -controlled loop uses a true/false condition to control the number of times that it repeats. Boolean condition decision count

condition

A. -controlled loop repeats a specific number of times. Boolean condition decision count

count

Nested loop example

def draw_rectangle(height, width, char): """ ------------------------------------------------------- Prints a rectangle of height and width characters using the char character. Use: draw_rectangle(height, width, char) ------------------------------------------------------- Parameters: height - number of characters high (int > 0) width - number of characters wide (int > 0) char - the character to draw with (str, len() == 1) Returns: None ------------------------------------------------------ """ for h in range (height): ##start w height for w in range (width): ## then width print (char, end= " ") print() #so it starts on a new line return None

Validation loops are also known as . error traps doomsday loops error avoidance loops defensive loops

error traps

A(n) is a special value that signals when there are no more items from a list of items to be processed. This value cannot be mistaken as an item from the list. sentinel flag signal accumulator

flag

If you pass one argument to the range function, that argument is used as the ending limit of the sequence of numbers. If you pass two arguments to the range function, the first argument is used as the starting value of the sequence, and the second argument is used as the ending limit. Here is an example:

for num in range(1, 5): print(num) 1 2 3 4

range example

for num in range(5): print(num) Notice instead of using a list of values, we call to the range function passing 5 as an argument. In this statement, the range function will generate an iterable sequence of integers in the range of 0 up to (but not including) 5. This code works the same as the following: for num in [0, 1, 2, 3, 4]: print(num)

for loop structure

for variable in [value1, value2, etc.]: statement statement The for statement executes in the following manner: The variable is assigned the first value in the list, then the statements that appear in the block are executed. Then, variable is assigned the next value in the list, and the statements in the block are executed again. This continues until variable has been assigned the last value in the list.

Rewrite the following code so it calls the range function instead of using the list [0, 1, 2, 3, 4, 5]

for x in [0, 1, 2, 3, 4, 5]: print('I love to program!') basically count items in list, thats how many times it will be printed for x in range(6): print('I love to program!')

Repetition - For Loops

for x in range (n): for x in range (a,b,i): for x in string: or in list

for x in range (n):

for x in range(5): print('Hello world') will print Hello world 5 times

GIGO stands for . great input, great output garbage in, garbage out GIGahertz Output GIGabyte Operation

garbage in, garbage out

\t

horizontal tab

A(n) loop has no way of ending and repeats until the program is interrupted. indeterminate interminable infinite timeless

infinite

The integrity of a program's output is only as good as the integrity of the program's compiler programming language input debugger

input

Iterable

is an object that is similar to a list. It contains a sequence of values that can be iterated over with something like a loop

Input validation

is the process of inspecting data that has been input to a program, to make sure it is valid before it is used in a computation. Input validation is commonly done with a loop that iterates as long as an input variable references bad data.

Each repetition of a loop is known as a(n) . cycle revolution orbit iteration

iteration

Infinite Loops

loops that have no end In all but rare cases, loops must contain within themselves a way to terminate. This means that something inside the loop must eventually make the test condition false. # Warning! Infinite loop! 6 while keep_going == 'y': 7 # Get a salesperson's sales and commission rate. 8 sales = float(input('Enter the amount of sales: ')) 9 comm_rate = float(input('Enter the commission rate: '))

A -controlled loop uses a true/false condition to control the number of times that it repeats.The while loop is a type of loop. pretest no-test prequalified post-iterative

pretest

The input operation that appears just before a validation loop is known as the . prevalidation read primordial read initialization read priming read

priming read

4.17 Rewrite the following statements using augmented assignment operators: quantity = quantity + 1 days_left = days_left − 5 price = price * 10 price = price / 2

quantity += 1 days_left -= 5 price *= 10 price /= 2

Generating an Iterable Sequence that Ranges from Highest to Lowest

range(10, 0, −1) 10, 9, 8, 7, 6, 5, 4, 3, 2, 1

repetition structure

the control structure used to repeatedly process one or more program instructions; also called a loop

****** ****** ****** ****** ****** ****** ****** ******

to make ****** for col in range(6): # 6 stars print('*', end=''). To complete the entire pattern, we need to execute this loop eight times. We can place the loop inside another loop that iterates eight times for row in range(8): for col in range(6): print('*', end='') print() The outer loop iterates eight times. Each time it iterates once, the inner loop iterates 6 times. (Notice in line 4, after each row has been printed, we call the print() function. We have to do that to advance the screen cursor to the next line at the end of each row. Without that statement, all the asterisks will be printed in one long row on the screen.)

for loop don't for get to add +1 to second variable if you want to include that number

total = 0 for i in range (start, finish+1, increment): total += i return total

condition-controlled loop

uses a true/false condition to control the number of times that it repeats

while loop format

while condition: statement statement When the while loop executes, the condition is tested. If the condition is true, the statements that appear in the block following the while clause are executed, and the loop starts over. If the condition is false, the program exits the loop.

Sentinel example

while lot ! = 0: # Get the property value. 14 value = float(input('Enter the property value: ')) Sentinel is 0 when the user puts 0 it will end the loop

Write a while loop that lets the user enter a number. The number should be multiplied by 10, and the result assigned to a variable named product. The loop should iterate as long as product is less than 100.

while product < 100:number = float(input('Enter a number:')) product = number * 10 (This input box does not allow indentation which should be on lines 2 & 3)

While Loop Example

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 Celsius temperature: ')) 1 # Remind the user to check the temperature again in 15 minutes. print('The temperature is acceptable.') print('Check it again in 15 minutes.')

Input Validation example

while wholesale < 0: print('ERROR: the cost cannot be negative.') wholesale = float(input('Enter the correct wholesale cost: '))

while loop with counter

x = 0 while x < 5: print(x) x += 1

while loop with sentinel

x = True while x == True: v = input("T/F?") if v != "T": x = False


Related study sets

Separation of Powers and Checks and Balances Quiz

View Set

Health Psych Exam 4 - Ch. 13 & 14

View Set

Aquifer FM End of Case Questions

View Set