Python Book 4 - Repetition Structures PDF
Document Details
Uploaded by ReliableAstronomy
Tags
Summary
This textbook covers core concepts in Python programming, focusing on repetition structures such as loops. It discusses condition-controlled loops (while loops) and count-controlled loops (for loops), along with practical examples and explanations of their application. The text provides a foundational understanding of loops in Python.
Full Transcript
Python Book 4 - REPETITION STRUCTURES Computer 521 Python Programming Book 4 1|Page Book 4 – Repetition Structures Programmers often have to write code that performs the same type of task over and over again. For...
Python Book 4 - REPETITION STRUCTURES Computer 521 Python Programming Book 4 1|Page Book 4 – Repetition Structures Programmers often have to write code that performs the same type of task over and over again. For example, suppose that you want to write a program that calculates a 15% sales commission for several salespeople. The program could be written by repeating certain sections of code over and over again. For instance, you could ask for the salesperson’s input information and then calculate the commission. Then you would repeat this code sequentially over and over again. This however is unnecessary and frowned upon. There are several disadvantages to duplicating code over and over again: - Duplicate code makes a program very large - It is very time consuming to create a large program with duplicate code - If part of the code has to be edited, it must be edited in several different places Programmers use a repetition structure which is commonly known as a loop to perform the same sequence of statements over and over again. The repetitive code is placed in the loop and the computer repeats the code as many times as necessary. Condition-Controlled and Count-Controlled Loops Two broad categories of loops are condition-controlled and count-controlled Loops. A condition- controlled loop uses a true/false condition to control the number of times that it repeats. A count- controlled loop repeats a specific number of times. Programmers use a while statement to write a condition-controlled loop and a for statement to write a count-controlled loop. The While Loop: A Condition-Controlled Loop A condition-controlled loop causes a statement or a set of statements to repeat as long as a condition is true. Programmers use a while statement to write a condition-controlled loop. A while loop works as long as a certain condition is true. The loop has two parts: (1) A condition that is tested for a true or false value, and (2) a statement or set of statements that is repeated as long as the condition is true. Here is the logic of a while loop: The diamond symbol represents the condition or expression that is tested. If the condition is true, a statement or a set of statements is executed and the program’s execution flows back to the point just Python Programming Book 4 2|Page above the diamond symbol. The condition is tested again, and if it is true, the process repeats itself. If the condition is false, the program exits the loop. Here is the general format of a while loop in Python: While condition: statement statement etc. The first line of code is often referred to as the while clause. The while clause begins with the word while, followed by a Boolean condition that will be evaluated as either true or false. A colon appears after the condition. A block of statements follows this code. The block of code is indented. This indentation is required because the Python interpreter uses it to tell where the block begins and ends. 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. Here is a program that calculates a salesperson’s commission using a while loop: Type the program into IDLE. Save it as Commission.py Run the program and debug it if necessary. Let’s take a look at the code: This program uses an assignment statement to create a variable named Keep_going that is assigned a string value of ‘y’. while keep_going == ‘y’ is the beginning of the while loop. The condition that is being tested is: keep_going == ‘y’. The loop tests this condition, and if it is true, the statements inside Python Programming Book 4 3|Page the loop are executed. All the statements that are indented after the while loop starts are executed. Then, the loop starts over again and if the condition keep_going == ‘y’ is true, the statements inside the loop are executed again. This cycle repeats until the expression keep_going == ‘y’ becomes false. When this happens, the program will exit the while loop. If something does not happen inside the loop to stop it from executing, the loop is considered to be an endless loop. So, something has to happen inside the while loop to make the expression or condition keep_going = ‘y’ false. At the end of the while loop, an input statement asks the user if they want to calculate another commission. If the user enters a lowercase y, the loop starts over again because the keep_going == ‘y’ condition is true. This will cause the statements in the body of the loop to be executed again. If the user enters anything other than a lowercase y, the expression will be false when the loop starts over and the program will exit the loop. Each execution of the body of a loop is known as an iteration. The loop will continue to execute until the condition keep_going == ‘y’ becomes false. Here is a flowchart of the program: Python Programming Book 4 4|Page The While Loop Is a Pretest Loop Many programmers refer to the while loop as a pretest loop, because it test its condition before performing an iteration. It tests for a condition at the beginning of the loop, so the programmer usually makes sure that the loop executes at least once. In our previous program, the loop starts with this code: while keep_going == ‘y’: The loop performs an iteration because the programmer assigned the value of the variable keep_going to ‘y’ prior to creating the code for the while loop. This forces the loop to iterate at least once. The while loop will never execute if its condition is false to start with. Infinite Loops If something within the loop does not make the test condition false, the loop is considered to be an endless loop or an infinite loop. The loop in our previous program stops when the expression keep_going == ‘y’ is false. The program contains some code inside the loop that can make this condition false. If it did not have this code, it would continue to repeat infinitely. Programmers try to avoid writing infinite loops. In the previous while loop program, try removing (just comment it out) the code that can make the while condition false. Run the program. This will create an endless loop because the loop has no way of stopping. In order to stop an endless loop, you must press Ctrl + C on the keyboard it interrupt it. The for Loop: A Count-Controlled Loop A count-controlled loop iterates a specific number of times. Programmers use the for statement to write a count-controlled loop. Count-controlled loops are commonly used by programmers. For example, suppose a theatre is open 5 days a week and you are writing a program that calculates the total seats sold for a week. You will need a loop that iterates exactly 5 times. Each time the loop iterates, it will prompt the user to enter the number of seats sold for one day. Programmers use the for statement to write a count-controlled loop. In Python, the for statement is designed to work with a sequence of data items. When a for statement executes, it iterates, or repeats once for each item in the sequence. The best way to understand a for loop structure is to type in a sample program that contains a for loop and then dissect the code. Type in the following program and run it. Save it as: simple_for_loop.py # This is a program that uses a simple for loop # It uses a list of numbers to do so # By Johnny LaRue, April 2, 2020 print(“This program will print the numbers 1 through 10.”) Python Programming Book 4 5|Page print() for myNumber in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: print(myNumber) Let’s take a look at the code. The first time that the for loop iterates, the value of the myNumber variable will be 1. It will print the number 1 on the screen. The next time the for loop iterates, the value of myNumber will be 2. It will print the number 2 on the screen. The for loop will continue to iterate printing the numbers 3, 4, 5, 6, 7, 8, 9 and 10. Once the myNumber value is assigned the last value in the list, the loop will terminate and program execution will be passed to the next line of code after the for loop. In our example, the program ends because there is no more code after the for loop. In our example the list contains 10 values, so the for loop will iterate 10 times. The first line of code in a for loop is refered to as the for clause. Python programmers often refer to the variable that is use in the for clause as the target variable because it is the target of an assignment at the beginning of each loop iteration. In our example, the target variable is myNumber. Now we are going to change some of the code in the previous program. Make sure that you change the for clause to look like this: print(“This program will print the odd numbers from 1 through 10.”) print() for myNumber in [1, 3, 5, 7, 9,]: Run the program. What do you notice about the output? Did it display the odd numbers that you wanted it to? This program demonstrates that you don’t have to have a consecutively ordered series of numbers in the list. The previous for loop iterated five times because there were five numbers in the list. Type in the following program and save it as: simpsons_for_loop.py # This is a program that uses a simple for loop # It uses a list of strings to do so # By Johnny LaRue, April 2, 2020 print() for cartoon_character in [‘Homer’, ‘Bart’, ‘Marge’, ‘Lisa’, ‘Maggie’]: print(cartoon_character) Run the program. In this example the for loop iterates over a list of strings. Since the list contains five strings, the for loop iterates five times. Using the range Function with the for Loop Python has a lot of built in functions which simplify the coding process. One of these function is the range function. Python programmers often use the range function to create count-controlled for loops. Python Programming Book 4 6|Page The range function creates a type of object known as an iterable. An 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 for loop. Type in the following program and save it as: simple_for_range.py # This is a program that uses a simple for loop # It uses the range function which is a built in function in Python # It prints a chant ten times # By Johnny LaRue, April 2, 2020 print(“The Montreal Canadians Rule!”) print() for myNumber in range(10): print(“Go Habs Go!”) This program will print “Go Habs Go!” ten times. The range function does not use a list of values. When we call the range function in the above program we pass 10 as an argument to the range function. This causes the range function to generate an iterable sequence of integers in the range of 0 up to (but not including) 10. The code in the above for loop works the same as the following code: for myNumber in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]: print(“Go Habs Go!) If we used this code, the for loop would iterate 10 times because there are 10 numbers in the list. If you pass one argument to the range function (like we did above), that argument is used as the ending limit of the sequence of numbers. We can also pass two arguments to the range function. If we do so, the first argument is used as the starting value of the sequence, and the second argument is used as the ending limit. It is best to try it in a program to understand it. Type in the following program and save it as: simple_for_range2.py # This is a program that uses a simple for loop # It uses a range function to do so # By Johnny LaRue, April 2, 2020 print(“This program will print the numbers 2 through 7.”) print() for myNumber in range(2, 8): print(myNumber) Run the program. What number did it the output start at? It starts at number two because we passed 2 as the first argument to the range function. The last number it printed was 7. This is because we passed Python Programming Book 4 7|Page 8 as the second argument to the range function. Remember that range function will print up to but not including 8. By default the range function produces a sequence of numbers that increment by 1 for each successive number in the list. If you pass a third argument to the range function, it will use this argument as a step value. Type in the following program and save it as: simple_for_range3.py # This is a program that uses a simple for loop # It uses the range function to do so # By Johnny LaRue, April 2, 2020 print(“This program will print the numbers 1 through 9 in a step value of 2”) print() for yourNumber in range(1, 10, 2): print(yourNumber) Let’s take a look at the for loop in this program. We passed three arguments to the range function. The first argument 1, is the starting value for the sequence. The second argument, 10, is the ending limit of the list. Remember that the range function will print up to but not including 10. As a result, the last number in the sequence will be 9. The third argument, 2, is the step value. So, two will be added to each successive number in the sequence. If you have typed in the program properly it should display the numbers 1, 3, 5, 7 and 9. Type in the following program and save it as: simple_for_square.py # This is a program uses a simple for loop to display a table showing # the numbers 1 through 10 and their squares # By Johnny LaRue, April 2, 2020 # table headings print(‘Number\tSquare’) print(‘---------------‘) # Print the numbers one through 10 and their squares for myNumber in range(1, 11): myNumberSquare = myNumber **2 print(myNumber, ‘\t’, myNumberSquare) Python Programming Book 4 8|Page Run the program. It should print a table showing the numbers 1 through 10 and the square of each number. Let’s take a look at the code. The for loop uses the range function to produce a sequence containing the numbers 1 through 10. On the first iteration of the for loop, myNumber will reference 1, and this value will step by one during each successive iteration of the for loop up to a value of 10. Inside the for loop a calculation raises the value of myNumber to the power of 2 (myNumberSquare = myNumber **2). The result is assigned to the variable called myNumberSquare. EXAMPLE PROGRAM: Designing a Count-Controlled Loop with the for Statement Let’s take a look at a practical example using a for loop. Save this program as: Kgs_to_Lbs.py You have been asked to create a program that displays a table of weights in kilograms with their values converted to pounds. The formula for converting kgs (kilograms) to lbs (pounds) is: lbs = kgs * 2.20462 The table that the program displays should show weights from 10 kgs to 100 kgs in increments of 5 kgs along with their values converted to lbs. The easiest way to create the table is by using a for loop. The list of values that the loop will iterate over will be the kgs. In the for loop you will call the range function like this: range(10, 101, 5) The first value in the sequence will be 10, the step value will be 5 and the ending limit will be 100. Inside the loop, the target variable is used to calculate the weight in lbs. Python Programming Book 4 9|Page The output should look like this: Letting the User Control the Loop Iterations Sometimes a programmer does not know the exact number of iterations that a loop must perform. In this case, the programmer needs to let the user control the number of times that a loop iterates. The next program shows how to let a user specify the maximum value displayed by a loop. Type in the following program and save it as: Kgs_to_Lbs2.py This program has been edited to allow the user to control the maximum weight in kgs that they want to convert to lbs. The expression end_kgs + 1 is used in the range function. We have to add one to end_kgs because if we did not, the sequence would go up to, but not include, the value entered by the user. Remember that the ending value goes up to (but not including) the end_kgs, which is the value that the user enters. Run the program and enter 200 for the maximum kg value. Take a look at the output. Notice that it includes the 200 kg maximum entered by the user. Python Programming Book 4 10 | P a g e The next program allows the user to enter the starting value and the ending limit of the sequence. Modify the code in your previous program to look like this and save it as: Kgs_to_Lbs3.py The following code has been added to the program as well: # reset starting kg weight to zero if user enters a negative number if start_kgs < 0: start_kgs = 0 Python Programming Book 4 11 | P a g e Python Programming Book 4 12 | P a g e Here is a sample output from the program: Generating an Iterable Sequence that Ranges from Highest to Lowest In all the examples that we have used so far, we have used the range function to generate a sequence of numbers that are in ascending order. The range function can also be used to generate a sequence of numbers that are in descending order. Here is an example: range(25, -1, -1) In this function call, the starting value is 25, the sequence’s ending limit is -1 and the step value is -1. This expression will produce the following sequence: 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 Python Programming Book 4 13 | P a g e The code to print the previous line of numbers is: for numbers in range(25, -1, -1): print(numbers) Calculating a Running Total A running total is a sum of numbers that accumulates with each iteration of a loop. The variable used to store the running total is called and accumulator. Sometimes programs require us to calculate the total of a series of numbers. If we were writing a program to calculate the total amount of students in all PEI high schools, we would capture the data from the keyboard and calculate a running total of all the students. In order to do this, we would need a loop to capture all the data about student population and a variable that accumulates the sum of the numbers as they are input from the keyboard. Here is the logic for calculating a running total: When the program exits the loop, the accumulator will contain the total of the numbers that the loop captured from the keyboard. It is critical that the program sets the accumulator variable to 0 prior to entering the loop. This ensures that the accumulator starts with a value of 0. If it does not, the accumulator will not contain the correct total when the loop finishes executing. Each time the loop iterates, it captures a number from the user and adds it to the accumulator. Python Programming Book 4 14 | P a g e Type in the following program and save it as: sum_numbers.py Run the program. Here is some sample output: Let’s take a look at the code: The total variable is used as an accumulator. It is initialized to 0 prior to entering the for loop. The for loop captures numbers from the user and accumulates the sum of all the numbers. The value that is captured from the user is assigned to a variable called number. The value in the number variable is added to the value in the total variable and it is then assigned back to the total variable. The computer always completes the right hand side of an assignment statement before assigning the value to the variable on the left side of the assignment statement. The value in the number variable is added to the total variable with each iteration of the for loop. When the for loop has completed executing, the total variable will contain the sum of all the numbers that the user entered. Python Programming Book 4 15 | P a g e The Augmented Assignment Operators An augmented assignment is generally used to replace a statement where an operator takes a variable as one of its arguments and then assigns the result back to the same variable. A simple example is x += 1 which is expanded to x = x + 1. We saw an example of this type of statement in the last program we constructed: total = number + total This statement assigns the value of number + total to total. The effect of this statement is that number is added to the value of total. It could have also been written as total += number. Here is another example: apples = apples – 1 This statement assigns the value of apples – 1 to the variable apples. Basically, apples is reduced by 1 and the value is reassigned to the variable apples. Some other examples of statements written this way in code are: x = x * 10 x=x/2 x=x%4 These types of operations are very common in many programming languages. For convenience, many programming languages, including Python, offer a special set of characters designed specifically for these jobs. Operator Example Usage Equivalent To += x += 5 x=x+5 -= x -= 5 x=x–5 *= x *= 5 x=x*5 /= x /= y x=x/y %= X %= 3 x=x%3 Augmented assignment operators are a sort of short cut because they do not require the programmer to type the variable name twice. total = total + mark can be rewritten as total += mark apples = apples -1 can be rewritten as apples -= 1 multiplier = multiplier * 5 can be rewritten as multiplier *= 5 Python Programming Book 4 16 | P a g e Sentinels A sentinel is a special value that marks the end of a sequence of items. Sentinel values are often used to terminate loops. An example would be where a user enters a certain value like -1 to terminate the addition of a sequence of numbers. The program could be adding the class marks for a test to determine the average mark (using a loop). The user would enter -1 as a mark and the program would interpret -1 as a signal that there are no more marks to process and the loop would end. In the above example, -1 is a good value to use as a sentinel because it is impossible to achieve a mark below 0 on a test. Programmers often use distinctive sentinel values that cannot be mistaken as regular program input. Let’s use a sentinel value in an actual program. We will also use augmented assignment operators in this program. Type in the following program and save it as: test_average.py Some typical output from the program is: Input Validation Loops Computers cannot tell the difference between good data and bad data. As a result, a computer program can process bad data and output bad data. It is the programmer’s responsibility to make sure that this does not happen. As a result, programmers try to design their programs in such a way that bad input is Python Programming Book 4 17 | P a g e never accepted. They do this by inspecting data input before it is processed. If the input is not valid, the program should not accept it and display a message prompting the user to enter the correct data. This process is known as input validation. One common technique for validating user input is to read the input and then validate it using a loop. If the users input data is bad, the loop will execute a block of statements and reject the bad data. The loop will display some type of error message to inform the user that they have input bad data. The program will then prompt the user for valid data. The loop will repeat over and over again until valid data is entered into the program. An input validation loop is sometimes called an error trap or an error handler. Here is the logic containing an input validation loop: Get user input Yes Is the Show error Get the input input message again invalid? ? No The flowchart reads the user input in two places: prior to the loop execution and then inside the loop. The first input operation that takes place just before an input validation loop is referred to as a priming read. The purpose of the priming read is to get the first input value that will be tested by the validation loop. If this input is invalid, the loop will display an error message and attempt to obtain valid data from the user. Let’ look at an example. You are creating a program that calculates the cost of shipping a package based on the weight of the package. In the code that appears below, the user enters a package weight. You want to make sure that the user does not enter a weight below zero. As a result, you write code that uses an input validation loop to reject any input data that has a negative value or a value of 0 (zero). # Get the package weight in Kgs Python Programming Book 4 18 | P a g e weight = float(input(“please enter the package weight in Kgs: ‘)) # validate the weight to make sure it is a positive value while weight