# 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(f'The commission is ${commission:,.2f}.') # See if the user wants to do another one. keep_going = input('Do you want to calculate another ' + 'commission (Enter y for yes): ')
The for Loop: a Count- Controlled Loop (1 of 2) • Count-Controlled loop: iterates a specific number of times Use a for statement to write count- controlled loop Designed to work with sequence of data items Iterates once for each item in the sequence General format: for variable in [val1, val2, etc]: statements Target variable: the variable which is the target of the assignment at the beginning of each iteration
Using the range Function with the for Loop • The range function simplifies the process of writing a for loop range returns an iterable object Iterable:contains a sequence of values that can be iterated over
• range characteristics: One argument: used as ending limit Two arguments: starting value and ending limit Three arguments: third argument is step value
Solution # 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(f'{number}\t{square}')
# 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(f'{number}\t{square}')
place them in variables, and call the range function in the for clause using these variables Besure to consider the end cases: range does not include the ending limit
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 end limit, and step value is negative Example: range(10, 0, -1)
Calculating a Running Total (1 of 2) • Programs often need to calculate a total of a series of numbers Typically include two elements: A loop that reads each number in series An accumulator variable
Known as program that keeps a running total:
accumulates total and reads in series At end of loop, accumulator will reference the total
The Augmented Assignment Operators (1 of 3) • In many assignment statements, the variable on the left side of the = operator also appears on the right side of the = operator
• Augmented assignment operators:
special set of operators designed for this type of job Shorthand operators
of a sequence of items When program reaches a sentinel, it knows that the end of the sequence of items was reached, and the loop terminates Must be distinctive enough so as not to be mistaken for a regular value in the sequence Example: when reading an input file, empty line can be used as a sentinel
between good data and bad data Ifuser provides bad input, program will produce bad output GIGO: garbage in, garbage out Itis important to design program such that bad input is never accepted
is processed by the program If input is invalid, prompt user to enter correct data Commonly accomplished using a while loop which repeats as long as the input is bad Ifinput is bad, display error message and receive another set of data Ifinput is good, continue to process the input
Example # Get a test score. score = int(input('Enter a test score: ')) # Make sure it is not less than 0 or greater than 100. while score < 0 or score > 100: print('ERROR: The score cannot be negative') print('or greater than 100.') score = int(input('Enter the correct score: '))
another loop Example: analog clock works like a nested loop Hours hand moves once for every twelve movements of the minutes hand: for each iteration of the “hours,” do twelve iterations of “minutes” Seconds hand moves 60 times for each movement of the minutes hand: for each iteration of “minutes,” do 60 iterations of “seconds”
Inner loop goes through all of its iterations for each iteration of outer loop Inner loops complete their iterations faster than outer loops Total number of iterations in nested loop:
number of iterations of inner loop X number of iterations of outer loop