Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
23 views
12 pages
Ch04 Iteration
Computer Python Learning
Uploaded by
wawerucollins15
AI-enhanced title
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
Download
Save
Save Ch04-Iteration For Later
Share
0%
0% found this document useful, undefined
0%
, undefined
Print
Embed
Report
0 ratings
0% found this document useful (0 votes)
23 views
12 pages
Ch04 Iteration
Computer Python Learning
Uploaded by
wawerucollins15
AI-enhanced title
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
Carousel Previous
Carousel Next
Download
Save
Save Ch04-Iteration For Later
Share
0%
0% found this document useful, undefined
0%
, undefined
Print
Embed
Report
Download
Save Ch04-Iteration For Later
You are on page 1
/ 12
Search
Fullscreen
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 prove46 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 last52 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
Codility Lessons
PDF
No ratings yet
Codility Lessons
48 pages
Python Mod2
PDF
No ratings yet
Python Mod2
93 pages
Lecture 5 Loop Structures
PDF
No ratings yet
Lecture 5 Loop Structures
74 pages
03 - Iteration and Strings
PDF
No ratings yet
03 - Iteration and Strings
48 pages
8 PythonFunctions
PDF
No ratings yet
8 PythonFunctions
186 pages
Lec 04
PDF
No ratings yet
Lec 04
54 pages
Lesson 4 Looping
PDF
No ratings yet
Lesson 4 Looping
56 pages
Chapter 4 PythonLoops
PDF
No ratings yet
Chapter 4 PythonLoops
28 pages
Py4Inf 05 Iterations
PDF
No ratings yet
Py4Inf 05 Iterations
39 pages
5 Iteration
PDF
No ratings yet
5 Iteration
24 pages
Python Loops
PDF
No ratings yet
Python Loops
33 pages
Unit 2
PDF
No ratings yet
Unit 2
29 pages
011 Loop 2024-25
PDF
No ratings yet
011 Loop 2024-25
67 pages
4 Python4-Iterations
PDF
No ratings yet
4 Python4-Iterations
48 pages
Looping Constructs
PDF
No ratings yet
Looping Constructs
43 pages
Topic 9. LOOPS IN PYTHON
PDF
No ratings yet
Topic 9. LOOPS IN PYTHON
40 pages
04 Python Lecture Updated
PDF
No ratings yet
04 Python Lecture Updated
35 pages
DMPP Loops
PDF
No ratings yet
DMPP Loops
21 pages
09 Iteration2
PDF
No ratings yet
09 Iteration2
21 pages
CSIT101 Lec3
PDF
No ratings yet
CSIT101 Lec3
29 pages
Week 3
PDF
No ratings yet
Week 3
52 pages
Python Note 8
PDF
No ratings yet
Python Note 8
24 pages
04 Repetition
PDF
No ratings yet
04 Repetition
27 pages
W6L2-ch04 Pr4.5-Pr4.6
PDF
No ratings yet
W6L2-ch04 Pr4.5-Pr4.6
29 pages
03 Iteration
PDF
No ratings yet
03 Iteration
33 pages
Module 3
PDF
No ratings yet
Module 3
39 pages
Final Python Notes
PDF
No ratings yet
Final Python Notes
63 pages
ProgFund Lect Week 5
PDF
No ratings yet
ProgFund Lect Week 5
25 pages
Topic 5 - Repetition Structures - Student
PDF
No ratings yet
Topic 5 - Repetition Structures - Student
37 pages
Lec5 Loops
PDF
No ratings yet
Lec5 Loops
29 pages
Py4inf 05 Iterations
PDF
No ratings yet
Py4inf 05 Iterations
39 pages
04 - Chapter 04
PDF
No ratings yet
04 - Chapter 04
26 pages
04 Repetition Structures
PDF
No ratings yet
04 Repetition Structures
15 pages
Itereative Statement - Ict Book Python
PDF
No ratings yet
Itereative Statement - Ict Book Python
8 pages
Python Notes
PDF
No ratings yet
Python Notes
9 pages
Lect 5-Loops
PDF
No ratings yet
Lect 5-Loops
25 pages
Ref Part 2
PDF
No ratings yet
Ref Part 2
8 pages
Pythonlearn. Chapter 5. Extract (69-78)
PDF
No ratings yet
Pythonlearn. Chapter 5. Extract (69-78)
10 pages
Lesson 2 and 3
PDF
No ratings yet
Lesson 2 and 3
10 pages
Control Flow
PDF
No ratings yet
Control Flow
18 pages
18CS752 - Python 3
PDF
No ratings yet
18CS752 - Python 3
18 pages
Python Lecture
PDF
No ratings yet
Python Lecture
36 pages
38891-Python 3 Iteration
PDF
No ratings yet
38891-Python 3 Iteration
10 pages
Loops and Iteration: Python For Informatics: Exploring Information
PDF
No ratings yet
Loops and Iteration: Python For Informatics: Exploring Information
52 pages
Module - 2: 2.1 Iteration
PDF
No ratings yet
Module - 2: 2.1 Iteration
19 pages
Module 1.2
PDF
No ratings yet
Module 1.2
29 pages
Marty Stepp (Stepp@cs - Washington.edu) Lecturer, Computer Science & Engineering University of Washington
PDF
No ratings yet
Marty Stepp (Stepp@cs - Washington.edu) Lecturer, Computer Science & Engineering University of Washington
32 pages
Iterations: 1.1. For Loops
PDF
No ratings yet
Iterations: 1.1. For Loops
4 pages
5 While Loop
PDF
No ratings yet
5 While Loop
5 pages
2024 25 COL100 Lab 6 Loops
PDF
No ratings yet
2024 25 COL100 Lab 6 Loops
9 pages
Introduction To Loops in Python
PDF
No ratings yet
Introduction To Loops in Python
6 pages
Intro To Loops in Python
PDF
No ratings yet
Intro To Loops in Python
5 pages
Lab # 4
PDF
No ratings yet
Lab # 4
16 pages
Chapter 4 - Iteration
PDF
No ratings yet
Chapter 4 - Iteration
10 pages
Python Chapter5
PDF
No ratings yet
Python Chapter5
22 pages
Loops and Iterations
PDF
No ratings yet
Loops and Iterations
4 pages
Loop and Iterations
PDF
No ratings yet
Loop and Iterations
20 pages
Module-5-INTEGRATIVE PROGRAMMING 2
PDF
No ratings yet
Module-5-INTEGRATIVE PROGRAMMING 2
10 pages
Form 1 4 Functional Writings Samples
PDF
No ratings yet
Form 1 4 Functional Writings Samples
58 pages
Turner
PDF
No ratings yet
Turner
3 pages
Hill. rs2020
PDF
No ratings yet
Hill. rs2020
11 pages
Ch03 Conditionals
PDF
No ratings yet
Ch03 Conditionals
12 pages
TKD2019 NAB A4-Preview
PDF
No ratings yet
TKD2019 NAB A4-Preview
1 page
Ch06 Strings
PDF
No ratings yet
Ch06 Strings
12 pages
Parallelism and Contrast Workshop
PDF
No ratings yet
Parallelism and Contrast Workshop
3 pages
Acting Fundamentals Brochure Optimized
PDF
No ratings yet
Acting Fundamentals Brochure Optimized
2 pages
Common Name of Water Hyacinth
PDF
No ratings yet
Common Name of Water Hyacinth
2 pages