0% found this document useful (0 votes)
23 views12 pages

Ch04 Iteration

Computer Python Learning

Uploaded by

wawerucollins15
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
23 views12 pages

Ch04 Iteration

Computer Python Learning

Uploaded by

wawerucollins15
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 12
Chapter 4 Iteration Computers are often used to automate repetitive tasks. Repeating identical or similar tasks without making errors is something that computers clo well and people do poorly. In a computer program, repetition is also called iteration, In this chapter we'll see two forms of iteration, the for loop and the wile loop. But first we want to say a little more about variable assignment. 4.1 Reassignment ‘As you may have discovered, it is legal to make more than one assignment to the same variable. A new assignment makes an existing variable refer to a new value (and stop referring to the old value). x5 . The first time we display x, its value is 5; the second time, its value is 7. Figure 4.1 shows what reassignment looks like in a state diagram. Ea Figure 4.1; State diagram, At this point I want to address a common source of confusion. Because Python uses the equal sign (-) for assignment, itis tempting to interpreta statement like a = basa mathe- ‘matical proposition of equality; that is, the claim that a and b are equal. But this interpre- tation is wrong. 2 Chapter Iteration First, equality is a symmetric relationship and assignment is not. For example, in math- ‘ematics, if a = 7 then 7 = a. But in Python, the statement a = 7 is legal and 7 = a is not Also, in mathematics, a proposition of equality is either true or false for all time. Ifa = & now, then awill always equal b. In Python, an assignment statement can make two vari- ables equal, but they don’t have to stay that way: aes Af a and b are nov equal S46 and b are no Longer equal The third line changes the value of a but does not change the value of b, so they are no longer equal Reassigning variables is often useful, but you should use it with caution. If the values of variables change frequently, it can make the code difficult to read and debug, 4.2 Updating variables A.common kind of reassignmentis an update, where the new value of the variable depends on the old ‘This means “get the current value of x, add one, and then update x with the new value.” If you try to update a variable that doesn’t exist, you get an error, because Python evaluates the right side before it assigns a value to x Before you can update a variable, you have to initialize it, usually with a simple assign- ment: =o Updating a variable by adding 1 is called an increment; subtracting 1 is called a decrement. 4.3. Simple repetition Assume that you want to print Hello 10 times, You could write in a script the following. code: Simple repetition [prine(Henie") ‘pein (-Hani") [prine("Heti0") prine(Holi0") [print (*Hti0") prine(Hoti0") [print ("Helio") rine (tHe120") rine (*Heto") rine (*Hett0) This works. However, it would be much more efficient (well, for us) if we could repeat instructions for a certain number of times. This ability is provided by the fox loop. We can do this with the following code: Zor i ja range(i0) print (Hlio") If you execute this, you will see it produces the desired output. Formally, the syntax for a for loop is the following Zor in : eeeay> This statement repeats for each element in the sequence and sets var to the element each. time. In the next few pages, we will provide you with lots of examples. Most will not have the output listed here. This is done for reasons of space, but also to encourage you to read the text with a Python interpreter open. Figure 4.2 shows the sequence of steps in a for loop. No Ye Figure 4.2: For loop flowchart. “4 Chapter 4. Iteration To count from 1 to 10, we can print out the index variable: igor 4 im range(ao) priac(.) This is an example of using an explicit list. We will cover lists in greater detail later in the text, Chapter 7. for iim 65,0, 1,2, 37 priae(s) and to print the squares of the odds: Yor oad i, 3, 5, 7, 9D rine (ode oad) ‘To see what range produces, one uses the following command: Bist range (i0)) So range can produce a counted loop. The range function is flexible. The general range command: range(start, end, step) range C10) ange(O, 10) Disk ange) 1,223, 45,6, 7, 8, 9) Taae range(5 100) 67,8 9) Dist range 10,2) 13.8, 7, 9) iat (range(20, 10,0) To, 19, 18, 17, 16, 15, 34, 33, 92, 10 Note that the range will count up to (down to) but not including the stop value. 43.1 Some looping examples Write code to sum the even numbers from 0 to 200. [for » in range(0,201,2) print (aun) Write a loop to sum all of the reciprocals from 1/2 to 1/100. Hfor in range(2,100) sun = sum ¢ 1.0/0 im) The vhile statement 45 44 The while statement The for statement we saw in Section 4.3 is one method of iteration, useful when iterating over a collection or when the number of repetitions is known. Another is the while statement, Here is a version of a countdown that uses a while state- ‘ment: finite a > 0: prince) prine (*Biaatotst") You can almost read the whie statement as ifit were English. It means, “While n is greater than 0, display the value of n and then decrement n. When you get to 0, display the word Blastoff!” More formally, here is the flow of execution for a vhile statement: 1. Determine whether the condition is true or false. 2. If false, exit the while statement and continue execution at the next statement, 3. If the condition is true, run the body and then go back to step 1 ‘This type of flow is called a loop because the third step loops back around to the top, ‘The body of the loop should change the value of one or more variables so that the condition eventually becomes false and the loop terminates. Otherwise the loop will repeat forever, which is called an infinite loop. An endless source of amusement for computer scientists is the observation that the directions on shampoo, “Lather, rinse, repeat”, are an infinite loop. In the case of the countdown above, we can prove that the loop terminates: if n is zero or negative, the loop never runs. Otherwise, a gets smaller each time through the loop, so eventually we have to get to 0. For some other loops, itis not so easy to tell. For example: fale n= a princ(a) Stn 2 = 0: # nis even nen/2 Jetse: # nis oft mieiaesee ‘The condition for this loop ism != 1, so the loop will continue until n is 1, which makes the condition false. Each time through the loop, the program outputs the value of n and then checks whether itis even or odd. If itis even, n is divided by 2. Ifit is odd, the value of nis replaced with ns3 + 1, For example, if the initial value of n is 3, the resulting values of n are 3, 10, 5, 16, 84,2, Since n sometimes increases and sometimes decreases, there is no obvious proof that n will ever reach 1, or that the loop terminates. For some particular values of n, we can prove 46 Chapter Iteration termination. For example, if the starting value is a power of two, 2 will be even every time through the loop until it reaches 1. ‘The hard question is whether we can prove that this loop terminates for all positive values of n. So far, no one has been able to prove it or disprove it! (See http: //en. wikipedia org/wiki/Collatz_conjecture.) 4.5 break Sometimes: In that case you don’t know it’s time to end a loop until you get half way through the body. ‘ou can use the break statement to jump out of the loop, For example, suppose you want to take input from the user until they type done, You could write Tine = tnpue(> print lise) print ‘Done! *) ‘The loop condition is True, which is always true, so the loop runs until it hits the break statement Each time through, it prompts the user with an angle bracket. If the user types dene, the break statement exits the loop. Otherwise the program echoes whatever the user types and. ‘goes back to the top of the loop. Here’s a sample run: > not done > done Done! ‘This way of writing shie loops is common because you can check the condition anywhere in the loop (not just at the top) and you can express the stop condition affirmatively ("stop ‘when this happens”) rather than negatively (“keep going until that happens”). 4.5.1 Input examples Write code to prompt the user for two values and checks if the two numbers satisfy (x + x ~ y) is positive. Keep asking if it does not. x= float input "Please enter x:")) y= float (input (Please enter 9:°)) St xen > y ‘break Prompt the user for a command string, ifthe string is "quit" then quit. Otherwise print the string and prompt again. 4.6, Square roots a7 faite Tree end = imput (Connand:") Af end == "quit ‘break ery pine (end) 2 Power conversion table For this example we write a program that generates a Horsepower to Watts conversion table, The program will prompt for the starting value of the table, the increment value for the table and the number of rows. We want the table to only have positive values and we will flag the user if there are any negative numbers entered. fact main patare = float(input (Eater the atarting horsepover: *)) piner = float (input ("Enter the sncrenent valve’ ")) rove = int (iaput ("Eater the nunber of rovs for the table: ")) Sf (hpstare <0) or (bpiner <0) or (rou < 0) prine(*Tavalia smpst") case! ‘break for 4 in range(0,roxs) bp = npaeare + ienpiner sates = 765, 7ehp print roud(hp,2),"hp = ", rouné(watts,2), "W* ) pein) 4.6 Square roots Loops are often used in programs that compute numerical results by starting with an ap- proximate answer and iteratively improving it. For example, one way of computing square roots is Newton's method. Suppose that you want to know the square root of a. If you start with almost any estimate, x, you can com- pute a better estimate with the following formula: _xta/x ya" For example, if ais 4 and x is 3: bstocmva > The result is closer to the correct answer (VI = 2). If we repeat the process with the new estimate it gets even closer: 48 Chapter 4. Iteration ey y= et arms y After a few more updates, the estimate is almost exact: ye +a /2 y = y y= et arms In general we don’t know ahead of time how many steps it takes to get to the right answer, but we know when we get there because the estimate stops changing: x= y y= tam so y 7 Stata s2 When y == x, we can stop. Here is a loop that starts with an initial estimate, x, and im- proves it until it stops changing: rine (a) yo Gran /2 For most values of a this works fine, but in general itis dangerous to test fleat equality. Most rational numbers, like 1/3, and irrational numbers, like v2, can't be represented exactly with a float Rather than checking whether x and y are exactly equal, itis safer to use the built-in func- tion abs to compute the absolute value, or magnitude, of the difference between them: TE aba(yo) © epsilon Where epsilon has a value like 0.000001 that determines how close is close enough. Nested Loops 49 4.7. Nested Loops You've seen how conditionals could be nested, one within another, In that case, the outer conditional would be evaluated, and if True the inner conditional would then be evaluated, Loops can also be nested. Each time the outermost loop executes, the inner loop will start anew iteration. Zor outer in range(@) princ( “outer Loop") for taney in vange(2) print( " inser 1o0p" ) sear oar deep snner 100p stethoe ‘ner 100p snner 1e0p outer 1099, ‘nner 160p nner 1e0p You can have any combination of for or vhile loops, depending on the needs of your program. Nested for loops are commonly used when manipulating two-dimensional data structures. 48 Algorithms Newton's method is an example of an algorithm: it is a mechanical process for solving a category of problems (in this case, computing square roots), To understand what an algorithm is, it might help to start with something that is not an algorithm. When you learned to multiply single-digit numbers, you probably memorized. the multiplication table, In effect, you memorized 100 specific solutions. That kind of knowledge is not algorithmic. But if you were “lazy”, you might have leamed a few tricks. For example, to find the product of and 9, you can write n — Las the first digit and 10 ~ n as the second digit. This trick is a general solution for multiplying any single-digit number by 9. That's an algorithm! ‘Similarly, the techniques you learned for addition with carrying, subtraction with borrow- ing, and long division are all algorithms. One of the characteristics of algorithms is that they do not require any intelligence to carry out, They are mechanical processes where each step follows from the last according to a simple set of rules. Executing algorithms is boring, but designing them is interesting, intellectually challeng- ing, and a central part of computer science. Some of the things that people do naturally, without difficulty or conscious thought, are the hardest to express algorithmically. Understanding natural language is a good example. We all do it, but so far no one has been able to explain how we do it, at least notin the form ofan algorithm. 50 Chapter 49 Debugging As you start writing bigger programs, you might find yourself spending more time debug- ging. More code means more chances to make an error and more places for bugs to hide. ‘One way to cut your debugging time is “debugging by bisection”. For example, if there are 100 lines in your program and you check them one at a time, it would take 100 steps. Instead, try to break the problem in half. Look at the middle of the program, or near it, for an intermediate value you can check. Add a print statement (or something else that has a verifiable effect) and run the program, If the mid-point check is incorrect, there must be a problem in the first half of the program. If itis correct, the problem is in the second half. Every time you perform a check like this, you halve the number of lines you have to search. After six steps (which is fewer than 100), you would be down to one or two lines of code, at least in theory. In practice itis not always clear what the “middle of the program” is and nat always pos- sible to check it. It doesn’t make sense to count lines and find the exact midpoint, Instead, ‘think about places in the program where there might be errors and places where it is easy to put a check, Then choose a spot where you think the chances are about the same that the bug is before or after the check 4.10 Glossary oop: A part of a program that can run repeatedly reassignment: Assigning a new value to a variable that already exists update: An assignment where the new value of the variable depends on the old initialization: An assignment that gives an initial value to a variable that will be updated, increment: An update that increases the value of a variable (often by one). decrement: An update that decreases the value of a variable iteration: Repeated execution of a set of statements using either a recursive function call or a loop. infinite loop: A loop in which the terminating condition is never satisfied. nested loops: Loops within other loops. algorithm: A general process for solving a category of problems. 4.11. Exercises 31 4.11 Exercises Exercise 1: Write a script named ay_eqrt.py using the loop from Section 4.6 and nest it inside a loop that uses a as the loop variable, running from 1 to 9. Choose a reasonable starting value of x for each iteration of a, and print a table like this: nysqrt (a) sqrt(a) ditt 1.0 1.0 1.0 0.0 2.0 1.41421386237 1.41421356237 2.22044604925e-16 3.0 1.73205080757 1.73205080757 0.0 4.0 2.0 2.0 0.0 5.0 2,2360679775 2.2360679775 0.0 6.0 2.a4948974278 2.44948974278 0.0 7.0 2.64575131106 2.64575131106 0.0 8.0 2.82842712475 2.82842712475 4.4408920985e-16 9.0 3.0 3.0 0.0 The first column is the number, a; the second column is the square root of a computed by your loop; the third column is the square root computed by nath. sqrt; the fourth column is the absolute value of the difference between the two estimates. Exercise 2: The built-in function eval takes a string and evaluates it using the Python interpreter. For example b> eval’ +2* 3") 7 >>> import math bo> eval (‘nath. sqrt (5)") 2.2360679774997898 >>> eval (type math pi) ") Write a script called eval Loop. py that iteratively prompts the user, takes the resulting input and evaluates it using eval, and prints the result. It should continue until the user enters ‘done’ Exercise ‘The mathematician Srinivasa Ramanujan found an infinite series that can be used to gen- erate a numerical approximation of 1/7: 1 _ av3 & (aiytttes + 263904) we 9501 2 (Fae Write a script called estinate_pi that uses this formula to compute and display an esti- mate of 7. Itshould use a while loop to compute terms of the summation tntil the last 52 Chapter 4. Iteration term is smaller than 1e-15 (which is Python notation for 10-15). You can check the result by comparing it to math. pi. Note that in mathematics, the symbol ! means factorial of a number, which is the prod- ‘uct of all integers from 1 up to and including the number. Python includes a function math factorial which will compute the factorial of a positive integer. Solution: http: //thinkpython?.com/code/pi py.

You might also like