Incorrect; Try Again; 4 Attempts Remaining Look Again at the Number of Iterations.
7. Iteration¶
Computers are frequently used to automate repetitive tasks. Repeating identical or similar tasks without making errors is something that computers do well and people practice poorly.
Repeated execution of a set of statements is called iteration. Considering iteration is so mutual, Python provides several language features to go far easier. Nosotros've already seen the for statement in chapter 3. This the the form of iteration you'll likely be using most oftentimes. But in this affiliate nosotros've going to look at the while statement — some other style to have your programme practise iteration, useful in slightly dissimilar circumstances.
Earlier we practice that, let's merely review a few ideas...
7.1. Consignment¶
Equally we accept mentioned previously, information technology is legal to make more than than one assignment to the same variable. A new assignment makes an existing variable refer to a new value (and stop referring to the sometime value).
airtime_remaining = xv print ( airtime_remaining ) airtime_remaining = 7 impress ( airtime_remaining )
The output of this program is:
considering the first time airtime_remaining is printed, its value is 15, and the 2nd fourth dimension, its value is seven.
It is especially important to distinguish betwixt an assignment statement and a Boolean expression that tests for equality. Because Python uses the equal token ( = ) for assignment, it is tempting to interpret a statement like a = b as a Boolean exam. Different mathematics, it is not! Think that the Python token for the equality operator is == .
Note too that an equality test is symmetric, only assignment is not. For example, if a == vii and then 7 == a . But in Python, the statement a = 7 is legal and 7 = a is non.
In Python, an assignment statement can brand 2 variables equal, but because farther assignments can change either of them, they don't have to stay that way:
a = 5 b = a # After executing this line, a and b are now equal a = three # Later on executing this line, a and b are no longer equal
The tertiary line changes the value of a merely does not alter the value of b , so they are no longer equal. (In some programming languages, a unlike symbol is used for assignment, such as <- or := , to avert confusion. Some people as well think that variable was an unfortunae give-and-take to cull, and instead we should have called them assignables. Python chooses to follow common terminology and token usage, also found in languages like C, C++, Coffee, and C#, so nosotros use the tokens = for consignment, == for equality, and nosotros talk of variables.
7.two. Updating variables¶
When an assignment statement is executed, the right-hand side expression (i.e. the expression that comes subsequently the assignment token) is evaluated first. This produces a value. So the assignment is fabricated, so that the variable on the left-manus side now refers to the new value.
One of the most common forms of consignment is an update, where the new value of the variable depends on its sometime value. Deduct 40 cents from my airtime balance, or add one run to the scoreboard.
Line 2 means go the current value of n, multiply information technology by three and add ane, and assign the answer to n, thus making north refer to the value. And then later on executing the two lines above, north volition point/refer to the integer 16.
If you try to get the value of a variable that has never been assigned to, you lot'll get an error:
>>> westward = x + i Traceback (most recent call terminal): File "<interactive input>", line 1, in NameError: name 'x' is not defined
Before you can update a variable, you have to initialize it to some starting value, usually with a simple assignment:
runs_scored = 0 ... runs_scored = runs_scored + 1
Line 3 — updating a variable by adding 1 to it — is very mutual. It is called an increment of the variable; subtracting 1 is called a decrement. Sometimes programmers also talk nigh bumping a variable, which means the same as incrementing it by 1.
7.3. The for loop revisited¶
Recall that the for loop processes each item in a list. Each detail in turn is (re-)assigned to the loop variable, and the trunk of the loop is executed. We saw this instance in an earlier affiliate:
for f in [ "Joe" , "Zoe" , "Brad" , "Angelina" , "Zuki" , "Thandi" , "Paris" ]: invitation = "Hullo " + f + ". Please come to my party on Sabbatum!" print ( invitation )
Running through all the items in a list is called traversing the list, or traversal.
Permit us write a role now to sum up all the elements in a list of numbers. Do this by hand offset, and try to isolate exactly what steps you lot have. Yous'll detect you lot need to keep some "running total" of the sum so far, either on a piece of newspaper, in your head, or in your reckoner. Remembering things from ane step to the next is precisely why we have variables in a program: so we'll demand some variable to remember the "running total". It should be initialized with a value of nothing, and so nosotros need to traverse the items in the list. For each item, we'll desire to update the running total by adding the next number to it.
1 2 3 4 five 6 seven 8 ix 10 xi 12 xiii def mysum ( xs ): """ Sum all the numbers in the list xs, and return the total. """ running_total = 0 for ten in xs : running_total = running_total + x return running_total # Add together tests like these to your examination suite ... examination ( mysum ([ 1 , ii , three , 4 ]) == 10 ) test ( mysum ([ i.25 , two.5 , 1.75 ]) == 5.5 ) examination ( mysum ([ 1 , - ii , 3 ]) == 2 ) test ( mysum ([ ]) == 0 ) examination ( mysum ( range ( 11 )) == 55 ) # xi is not included in the list.
7.4. The while statement¶
Hither is a fragment of lawmaking that demonstrates the use of the while statement:
1 2 3 iv 5 half-dozen seven 8 9 10 11 12 def sum_to ( n ): """ Return the sum of i+ii+3 ... northward """ ss = 0 v = 1 while v <= n : ss = ss + v v = v + 1 return ss # For your test suite exam ( sum_to ( 4 ) == 10 ) test ( sum_to ( 1000 ) == 500500 )
You can almost read the while statement as if it were English. It means, while five is less than or equal to n , continue executing the body of the loop. Inside the body, each fourth dimension, increment 5 . When v passes north , return your accumulated sum.
More formally, here is precise flow of execution for a while statement:
- Evaluate the condition at line 5, yielding a value which is either False or True .
- If the value is Faux , get out the while statement and continue execution at the side by side argument (line eight in this example).
- If the value is True , execute each of the statements in the body (lines 6 and vii) and then get back to the while statement at line v.
The body consists of all of the statements indented beneath the while keyword.
Discover that if the loop condition is False the outset fourth dimension we get loop, the statements in the trunk of the loop are never executed.
The body of the loop should change the value of one or more variables then that eventually the status becomes simulated and the loop terminates. Otherwise the loop will repeat forever, which is chosen an space loop. An countless source of amusement for computer scientists is the observation that the directions on shampoo, "lather, rinse, repeat", are an infinite loop.
In the example here, nosotros can prove that the loop terminates considering we know that the value of n is finite, and nosotros can see that the value of v increments each time through the loop, so eventually it will have to exceed n . In other cases, it is not so easy, even incommunicable in some cases, to tell if the loop will e'er terminate.
What you lot will notice here is that the while loop is more work for you — the programmer — than the equivalent for loop. When using a while loop 1 has to manage the loop variable yourself: requite information technology an initial value, test for completion, and then make sure you modify something in the body so that the loop terminates. Past comparing, here is an equivalent function that uses for instead:
def sum_to ( n ): """ Return the sum of ane+2+3 ... n """ ss = 0 for 5 in range ( n + 1 ): ss = ss + v return ss
Discover the slightly catchy call to the range function — we had to add one onto n , because range generates its list up to but excluding the value you give information technology. It would be easy to brand a programming mistake and overlook this, but because we've made the investment of writing some unit tests, our test suite would have caught our error.
So why have 2 kinds of loop if for looks easier? This next example shows a case where we demand the actress power that we go from the while loop.
seven.5. The Collatz 3n + 1 sequence¶
Let's look at a simple sequence that has fascinated and foxed mathematicians for many years. They however cannot respond fifty-fifty quite uncomplicated questions about this.
The "computational rule" for creating the sequence is to starting time from some given n , and to generate the adjacent term of the sequence from northward , either by halving northward , (whenever n is fifty-fifty), or else by multiplying it by three and calculation 1. The sequence terminates when n reaches 1.
This Python function captures that algorithm:
def seq3np1 ( n ): """ Print the 3n+i sequence from n, terminating when it reaches 1. """ while n != one : print ( n , finish = ", " ) if n % 2 == 0 : # north is even northward = n // two else : # northward is odd n = n * three + i print ( n , end = ". \n " )
Notice first that the impress function on line 6 has an extra argument terminate=", " . This tells the print function to follow the printed string with whatever the programmer chooses (in this case, a comma followed by a space), instead of ending the line. So each time something is printed in the loop, information technology is printed on the aforementioned output line, with the numbers separated by commas. The telephone call to print(n, end=".\n") at line 11 afterwards the loop terminates will and so print the final value of n followed by a flow and a newline character. (Y'all'll cover the \due north (newline graphic symbol) in the side by side chapter).
The condition for continuing with this loop is due north != 1 , so the loop will keep running until it reaches its termination condition, (i.eastward. northward == 1 ).
Each time through the loop, the program outputs the value of northward and and so checks whether it is fifty-fifty or odd. If information technology is fifty-fifty, the value of due north is divided by 2 using integer division. If information technology is odd, the value is replaced by n * 3 + 1 . Hither are some examples:
>>> seq3np1 ( 3 ) 3, 10, five, 16, 8, 4, two, ane. >>> seq3np1 ( 19 ) 19, 58, 29, 88, 44, 22, xi, 34, 17, 52, 26, 13, 40, twenty, 10, v, 16, viii, 4, 2, 1. >>> seq3np1 ( 21 ) 21, 64, 32, sixteen, viii, four, ii, one. >>> seq3np1 ( 16 ) sixteen, 8, iv, ii, 1. >>>
Since n sometimes increases and sometimes decreases, there is no obvious proof that due north will always reach ane, or that the programme terminates. For some particular values of n , we can prove termination. For instance, if the starting value is a power of two, then the value of n volition be even each fourth dimension through the loop until it reaches one. The previous example ends with such a sequence, starting with xvi.
See if you can observe a small starting number that needs more than a hundred steps before it terminates.
Particular values aside, the interesting question was showtime posed by a German mathematician called Lothar Collatz: the Collatz conjecture (also known equally the 3n + i theorize), is that this sequence terminates for all positive values of n . So far, no one has been able to prove it or disprove it! (A conjecture is a argument that might be truthful, but nobody knows for sure.)
Retrieve carefully about what would exist needed for a proof or disproof of the conjecture "All positive integers volition eventually converge to 1 using the Collatz rules". With fast computers we accept been able to test every integer upward to very large values, so far, they have all somewhen ended up at 1. But who knows? Perhaps there is some equally-yet untested number which does non reduce to i.
You'll detect that if you don't terminate when you lot reach ane, the sequence gets into its ain circadian loop: 1, 4, 2, 1, 4, 2, i, iv ... So 1 possibility is that there might exist other cycles that we just haven't found withal.
Wikipedia has an informative article about the Collatz conjecture. The sequence also goes under other names (Hailstone sequence, Wonderous numbers, etc.), and you'll find out just how many integers have already been tested by computer, and found to converge!
Choosing between for and while
Use a for loop if you know, before you kickoff looping, the maximum number of times that you'll need to execute the trunk. For instance, if you're traversing a list of elements, you know that the maximum number of loop iterations y'all tin possibly need is "all the elements in the list". Or if y'all need to print the 12 times tabular array, we know right abroad how many times the loop will demand to run.
So any problem similar "iterate this weather model for 1000 cycles", or "search this list of words", "observe all prime numbers upwardly to 10000" propose that a for loop is best.
By contrast, if you are required to repeat some computation until some condition is met, and you cannot calculate in advance when (of if) this will happen, as nosotros did in this 3n + 1 trouble, you'll need a while loop.
Nosotros phone call the outset instance definite iteration — we know ahead of time some definite bounds for what is needed. The latter case is called indefinite iteration — we're not certain how many iterations we'll need — nosotros cannot even constitute an upper bound!
7.half dozen. Tracing a programme¶
To write effective calculator programs, and to build a good conceptual model of program execution, a programmer needs to develop the ability to trace the execution of a computer plan. Tracing involves condign the computer and post-obit the menstruation of execution through a sample program run, recording the country of all variables and whatever output the program generates afterwards each teaching is executed.
To understand this process, allow's trace the call to seq3np1(3) from the previous section. At the outset of the trace, nosotros have a variable, n (the parameter), with an initial value of three. Since 3 is not equal to 1, the while loop body is executed. three is printed and 3 % ii == 0 is evaluated. Since it evaluates to Simulated , the else branch is executed and 3 * 3 + 1 is evaluated and assigned to n .
To keep rail of all this equally y'all hand trace a program, make a column heading on a piece of paper for each variable created as the programme runs and some other one for output. Our trace then far would look something like this:
n output printed and then far -- --------------------- three 3, 10
Since ten != one evaluates to True , the loop body is again executed, and x is printed. 10 % 2 == 0 is true, then the if branch is executed and n becomes 5. Past the end of the trace nosotros have:
north output printed and then far -- --------------------- three 3, 10 three, 10, 5 iii, x, 5, 16 three, 10, 5, 16, 8 iii, 10, v, 16, viii, iv iii, ten, five, 16, 8, iv, ii 3, 10, 5, xvi, 8, 4, 2, i 3, 10, v, sixteen, eight, 4, 2, ane.
Tracing can be a flake tedious and error decumbent (that's why we get computers to exercise this stuff in the first place!), but it is an essential skill for a programmer to have. From this trace we can learn a lot about the fashion our code works. We can observe that as presently as n becomes a power of 2, for example, the program will require log2(n) executions of the loop body to complete. We can also see that the final 1 will not exist printed as output within the body of the loop, which is why nosotros put the special print function at the terminate.
Tracing a programme is, of course, related to single-stepping through your lawmaking and being able to inspect the variables. Using the computer to single-step for you is less error prone and more convenient. Besides, as your programs get more complex, they might execute many millions of steps before they get to the code that you lot're really interested in, then manual tracing becomes incommunicable. Existence able to fix a breakpoint where y'all need one is far more powerful. Then we strongly encourage you to invest time in learning using to utilize your programming environment (PyScripter, in these notes) to full result.
At that place are also some swell visualization tools becoming available to help yous trace and understand small fragments of Python code. The i we recommend is at http://netserv.ict.ru.air conditioning.za/python3_viz
We've cautioned against chatterbox functions, merely used them hither. Equally we learn a bit more Python, nosotros'll be able to testify you lot how to generate a list of values to hold the sequence, rather than having the function impress them. Doing this would remove the need to have all these pesky print functions in the middle of our logic, and will make the function more than useful.
seven.7. Counting digits¶
The following role counts the number of decimal digits in a positive integer:
def num_digits ( n ): count = 0 while northward != 0 : count = count + 1 n = n // ten return count
A call to impress(num_digits(710)) will print three . Trace the execution of this function call (perhaps using the single step function in PyScripter, or the Python visualizer, or on some newspaper) to convince yourself that information technology works.
This function demonstrates an important design of computation chosen a counter. The variable count is initialized to 0 and so incremented each time the loop body is executed. When the loop exits, count contains the outcome — the total number of times the loop body was executed, which is the same as the number of digits.
If we wanted to only count digits that are either 0 or 5, adding a conditional before incrementing the counter will do the pull a fast one on:
def num_zero_and_five_digits ( n ): count = 0 while n > 0 : digit = northward % x if digit == 0 or digit == 5 : count = count + 1 n = n // ten return count
Confirm that examination(num_zero_and_five_digits(1055030250) == 7) passes.
Detect, however, that test(num_digits(0) == ane) fails. Explicate why. Practise you remember this is a bug in the code, or a bug in the specifications, or our expectations, or the tests?
7.8. Abbreviated assignment¶
Incrementing a variable is so common that Python provides an abbreviated syntax for it:
>>> count = 0 >>> count += 1 >>> count 1 >>> count += i >>> count 2
count += 1 is an abreviation for count = count + one . Nosotros pronounce the operator as "plus-equals". The increment value does non have to exist 1:
>>> north = 2 >>> northward += v >>> n 7
In that location are like abbreviations for -= , *= , /= , //= and %= :
>>> n = two >>> due north *= five >>> n ten >>> n -= 4 >>> n 6 >>> northward //= 2 >>> n 3 >>> n %= 2 >>> n one
7.x. Tables¶
Ane of the things loops are good for is generating tables. Before computers were readily bachelor, people had to summate logarithms, sines and cosines, and other mathematical functions by hand. To brand that easier, mathematics books independent long tables list the values of these functions. Creating the tables was slow and boring, and they tended to be full of errors.
When computers appeared on the scene, one of the initial reactions was, "This is nifty! Nosotros can utilise the computers to generate the tables, so there will be no errors." That turned out to be truthful (mostly) but shortsighted. Soon thereafter, computers and calculators were and then pervasive that the tables became obsolete.
Well, near. For some operations, computers use tables of values to go an guess answer and then perform computations to improve the approximation. In some cases, in that location accept been errors in the underlying tables, most famously in the table the Intel Pentium processor fleck used to perform floating-point division.
Although a log table is not as useful every bit it one time was, it nonetheless makes a good example of iteration. The following plan outputs a sequence of values in the left column and 2 raised to the power of that value in the right cavalcade:
for ten in range ( xiii ): # Generate numbers 0 to 12 print ( x , " \t " , 2 ** x )
The string "\t" represents a tab grapheme. The backslash character in "\t" indicates the starting time of an escape sequence. Escape sequences are used to stand for invisible characters similar tabs and newlines. The sequence \north represents a newline.
An escape sequence can appear anywhere in a cord; in this example, the tab escape sequence is the only thing in the string. How practise you lot call up y'all represent a backslash in a cord?
As characters and strings are displayed on the screen, an invisible marker called the cursor keeps track of where the next character will become. After a impress function, the cursor normally goes to the starting time of the next line.
The tab grapheme shifts the cursor to the right until it reaches one of the tab stops. Tabs are useful for making columns of text line upwardly, as in the output of the previous program:
0 i one 2 ii 4 3 8 iv 16 5 32 6 64 seven 128 8 256 9 512 10 1024 11 2048 12 4096
Considering of the tab characters betwixt the columns, the position of the second column does not depend on the number of digits in the starting time column.
seven.11. Two-dimensional tables¶
A two-dimensional table is a table where you read the value at the intersection of a row and a column. A multiplication tabular array is a good example. Permit'due south say you lot desire to impress a multiplication table for the values from 1 to 6.
A skillful way to start is to write a loop that prints the multiples of 2, all on ane line:
for i in range ( 1 , vii ): impress ( two * i , end = " " ) impress ()
Here nosotros've used the range role, but made it offset its sequence at 1. As the loop executes, the value of i changes from i to 6. When all the elements of the range accept been assigned to i , the loop terminates. Each fourth dimension through the loop, it displays the value of two * i , followed past three spaces.
Again, the actress end=" " argument in the print function suppresses the newline, and uses three spaces instead. Later on the loop completes, the call to print at line three finishes the current line, and starts a new line.
The output of the programme is:
So far, so good. The next stride is to encapsulate and generalize.
vii.12. Encapsulation and generalization¶
Encapsulation is the process of wrapping a piece of code in a function, allowing you lot to take reward of all the things functions are good for. You take already seen some examples of encapsulation, including is_divisible in a previous chapter.
Generalization means taking something specific, such as press the multiples of 2, and making it more full general, such equally printing the multiples of whatever integer.
This part encapsulates the previous loop and generalizes information technology to print multiples of n :
def print_multiples ( north ): for i in range ( 1 , 7 ): print ( n * i , end = " " ) print ()
To encapsulate, all we had to exercise was add the first line, which declares the name of the part and the parameter list. To generalize, all we had to do was replace the value two with the parameter n .
If we phone call this role with the argument 2, we get the same output every bit before. With the statement 3, the output is:
With the argument 4, the output is:
Past now you can probably guess how to print a multiplication table — by calling print_multiples repeatedly with different arguments. In fact, we tin use another loop:
for i in range ( ane , 7 ): print_multiples ( i )
Notice how similar this loop is to the one within print_multiples . All we did was replace the print function with a part call.
The output of this plan is a multiplication table:
1 2 3 4 v 6 2 4 6 8 10 12 3 vi 9 12 15 18 four 8 12 xvi 20 24 v 10 15 20 25 thirty 6 12 18 24 30 36
7.xiii. More than encapsulation¶
To demonstrate encapsulation once more, let'due south take the code from the last section and wrap information technology upwardly in a function:
def print_mult_table (): for i in range ( 1 , 7 ): print_multiples ( i )
This process is a common development plan. Nosotros develop code by writing lines of code exterior whatever function, or typing them in to the interpreter. When we go the code working, we extract information technology and wrap information technology upwardly in a part.
This development plan is especially useful if you don't know how to divide the program into functions when you start writing. This approach lets you design equally you lot go along.
seven.14. Local variables¶
You might be wondering how nosotros can use the aforementioned variable, i , in both print_multiples and print_mult_table . Doesn't it cause problems when one of the functions changes the value of the variable?
The answer is no, considering the i in print_multiples and the i in print_mult_table are not the same variable.
Variables created inside a function definition are local; you tin't access a local variable from outside its home part. That means you are costless to have multiple variables with the aforementioned name as long as they are not in the same function.
Python examines all the statements in a part — if whatever of them assign a value to a variable, that is the clue that Python uses to make the variable a local variable.
The stack diagram for this program shows that the two variables named i are non the same variable. They can refer to dissimilar values, and irresolute 1 does not touch the other.
The value of i in print_mult_table goes from i to six. In the diagram it happens to exist 3. The next time through the loop it volition be 4. Each time through the loop, print_mult_table calls print_multiples with the current value of i as an argument. That value gets assigned to the parameter n .
Within print_multiples , the value of i goes from 1 to six. In the diagram, information technology happens to exist 2. Changing this variable has no effect on the value of i in print_mult_table .
It is common and perfectly legal to have dissimilar local variables with the same name. In particular, names similar i and j are used ofttimes as loop variables. If y'all avoid using them in 1 office simply because you used them somewhere else, y'all will probably make the plan harder to read.
The visualizer at http://netserv.ict.ru.ac.za/python3_viz/ shows very conspicuously how the two variables i are distinct variables, and how they take independent values.
7.15. The break argument¶
The break statement is used to immediately go out the trunk of its loop. The adjacent statement to be executed is the start one after the body:
for i in [ 12 , sixteen , 17 , 24 , 29 ]: if i % 2 == 1 : # If the number is odd break # ... immediately go out the loop print ( i ) impress ( "done" )
This prints:
The pre-test loop — standard loop behaviour
for and while loops do their tests at the start, before executing whatsoever part of the trunk. They're chosen pre-test loops, because the test happens before (pre) the body. break and return are our tools for adapting this standard behaviour.
7.sixteen. Other flavours of loops¶
Sometimes we'd like to have the center-test loop with the exit test in the center of the torso, rather than at the beginning or at the end. Or a post-test loop that puts its exit test as the last thing in the body. Other languages accept different syntax and keywords for these different flavours, but Python just uses a combination of while and if condition: suspension to get the job done.
A typical example is a problem where the user has to input numbers to exist summed. To indicate that there are no more inputs, the user enters a special value, often the value -1, or the empty cord. This needs a heart-get out loop pattern: input the adjacent number, then test whether to go out, or else process the number:
The middle-test loop flowchart
total = 0 while True : response = input ( "Enter the next number. (Exit blank to end)" ) if response == "" : break total += int ( response ) print ( "The total of the numbers you entered is " , full )
Convince yourself that this fits the middle-get out loop flowchart: line 3 does some useful piece of work, lines 4 and 5 can leave the loop, and if they don't line 6 does more useful work before the next iteration starts.
The while bool-expr: uses the Boolean expression to determine whether to iterate again. Truthful is a trivial Boolean expression, and then while Truthful: means always practise the loop body again. This is a language idiom — a convention that most programmers will recognize immediately. Since the expression on line 2 will never end the loop, (it is a dummy test) the programmer must accommodate to suspension (or return) out of the loop body elsewhere, in another manner (i.e. in lines 4 and 5 in this sample). A clever compiler or interpreter will understand that line two is a simulated test that must ever succeed, and then information technology won't fifty-fifty generate a exam, and our flowchart never even put the diamond-shape dummy test box at the superlative of the loop!
Similarly, by merely moving the if status: suspension to the end of the loop body we create a design for a post-test loop. Post-examination loops are used when you desire to be sure that the loop body always executes at least once (considering the first exam just happens at the stop of the execution of the starting time loop body). This is useful, for example, if we want to play an interactive game confronting the user — nosotros always want to play at least ane game:
while True : play_the_game_once () response = input ( "Play once again? (aye or no)" ) if response != "aye" : break print ( "Goodbye!" )
Hint: Think about where you want the leave test to happen
Once y'all've recognized that you need a loop to repeat something, think near its terminating condition — when will I want to stop iterating? And so figure out whether you need to practise the examination earlier starting the first (and every other) iteration, or at the finish of the commencement (and every other) iteration, or maybe in the centre of each iteration. Interactive programs that require input from the user or read from files often need to get out their loops in the middle or at the end of an iteration, when it becomes clear that at that place is no more data to process, or the user doesn't want to play our game anymore.
seven.17. An case¶
The following program implements a simple guessing game:
one 2 3 4 5 vi 7 viii 9 10 xi 12 thirteen 14 xv 16 17 18 import random # Nosotros cover random numbers in the rng = random . Random () # modules affiliate, so peek ahead. number = rng . randrange ( i , k ) # Get random number between [i and 1000). guesses = 0 msg = "" while True : guess = int ( input ( msg + " \n Judge my number between 1 and 1000: " )) guesses += 1 if guess > number : msg += str ( guess ) + " is too high. \northward " elif judge < number : msg += str ( guess ) + " is too low. \due north " else : interruption input ( " \due north\n Great, yous got it in {0} guesses! \n\north " . format ( guesses ))
This plan makes apply of the mathematical law of trichotomy (given existent numbers a and b, exactly one of these three must be truthful: a > b, a < b, or a == b).
At line 18 at that place is a phone call to the input role, but nosotros don't do annihilation with the result, not even assign information technology to a variable. This is legal in Python. Here it has the effect of popping upward the input dialog window and waiting for the user to respond earlier the program terminates. Programmers often use the flim-flam of doing some extra input at the cease of a script, just to continue the window open.
Also observe the use of the msg variable, initially an empty cord, on lines 6, 12 and 14. Each time through the loop nosotros extend the message being displayed: this allows us to display the programme's feedback right at the same place as we're request for the next guess.
7.18. The continue argument¶
This is a control catamenia argument that causes the program to immediately skip the processing of the rest of the torso of the loop, for the current iteration. Simply the loop still carries on running for its remaining iterations:
for i in [ 12 , 16 , 17 , 24 , 29 , thirty ]: if i % two == i : # If the number is odd continue # Don't process information technology print ( i ) impress ( "done" )
This prints:
7.19. More than generalization¶
Every bit another example of generalization, imagine you wanted a plan that would print a multiplication table of whatever size, not just the 6-by-six tabular array. You could add a parameter to print_mult_table :
def print_mult_table ( high ): for i in range ( 1 , high + 1 ): print_multiples ( i )
Nosotros replaced the value 7 with the expression loftier+1 . If nosotros call print_mult_table with the argument 7, it displays:
1 ii iii four 5 6 2 4 6 viii x 12 3 six ix 12 fifteen xviii 4 8 12 16 20 24 5 x 15 20 25 30 half dozen 12 xviii 24 thirty 36 vii 14 21 28 35 42
This is fine, except that we probably want the table to exist square — with the same number of rows and columns. To practice that, nosotros add another parameter to print_multiples to specify how many columns the table should have.
Simply to be annoying, nosotros call this parameter high , demonstrating that different functions tin can have parameters with the same name (but like local variables). Here's the whole plan:
def print_multiples ( n , high ): for i in range ( 1 , high + ane ): print ( n * i , stop = " " ) print () def print_mult_table ( loftier ): for i in range ( one , high + one ): print_multiples ( i , high )
Notice that when nosotros added a new parameter, nosotros had to change the starting time line of the role (the function heading), and nosotros also had to change the place where the role is called in print_mult_table .
Now, when we call print_mult_table(7) :
1 2 3 4 5 6 seven 2 iv 6 eight 10 12 xiv three vi 9 12 15 18 21 four viii 12 xvi 20 24 28 five 10 15 20 25 30 35 half dozen 12 eighteen 24 30 36 42 7 14 21 28 35 42 49
When y'all generalize a function appropriately, you lot often get a program with capabilities you didn't program. For case, you might notice that, because ab = ba, all the entries in the table appear twice. Yous could save ink by printing simply one-half the table. To do that, you lot merely have to change one line of print_mult_table . Change
print_multiples ( i , high + 1 )
to
and yous get:
one two 4 iii 6 9 4 8 12 sixteen v ten 15 20 25 6 12 eighteen 24 30 36 seven 14 21 28 35 42 49
seven.xx. Functions¶
A few times at present, we accept mentioned all the things functions are practiced for. By now, you might be wondering what exactly those things are. Here are some of them:
- Capturing your mental chunking. Breaking your complex tasks into sub-tasks, and giving the sub-tasks a meaningful name is a powerful mental technique. Expect back at the example that illustrated the post-test loop: nosotros assumed that we had a role called play_the_game_once . This chunking allowed u.s. to put aside the details of the detail game — is it a card game, or noughts and crosses, or a role playing game — and simply focus on one isolated office of our program logic — letting the player cull whether they desire to play again.
- Dividing a long program into functions allows y'all to separate parts of the program, debug them in isolation, and then compose them into a whole.
- Functions facilitate the employ of iteration.
- Well-designed functions are frequently useful for many programs. Once you write and debug one, you can reuse information technology.
7.21. Paired Data¶
We've already seen lists of names and lists of numbers in Python. We're going to peek ahead in the textbook a piddling, and bear witness a more advanced way of representing our data. Making a pair of things in Python is as simple as putting them into parentheses, like this:
year_born = ( "Paris Hilton" , 1981 )
Nosotros tin can put many pairs into a listing of pairs:
celebs = [( "Brad Pitt" , 1963 ), ( "Jack Nicholson" , 1937 ), ( "Justin Bieber" , 1994 )]
Here is a quick sample of things we can exercise with structured data similar this. First, print all the celebs:
print ( celebs ) print ( len ( celebs ))[("Brad Pitt", 1963), ("Jack Nicholson", 1937), ("Justin Bieber", 1994)] 3
Detect that the celebs list has but three elements, each of them pairs.
Now we impress the names of those celebrities built-in before 1980:
for ( nm , year ) in celebs : if yr < 1980 : print ( nm )
This demonstrates something we have not seen even so in the for loop: instead of using a single loop control variable, we've used a pair of variable names, (nm, yr) , instead. The loop is executed 3 times — once for each pair in the list, and on each iteration both the variables are assigned values from the pair of data that is being handled.
vii.22. Nested Loops for Nested Data¶
Now we'll come up with an even more than adventurous list of structured data. In this case, nosotros take a list of students. Each pupil has a name which is paired up with another list of subjects that they are enrolled for:
students = [ ( "John" , [ "CompSci" , "Physics" ]), ( "Vusi" , [ "Maths" , "CompSci" , "Stats" ]), ( "Jess" , [ "CompSci" , "Bookkeeping" , "Economic science" , "Direction" ]), ( "Sarah" , [ "InfSys" , "Bookkeeping" , "Economics" , "CommLaw" ]), ( "Zuki" , [ "Sociology" , "Economics" , "Law" , "Stats" , "Music" ])]
Hither nosotros've assigned a list of five elements to the variable students . Let'south print out each student proper noun, and the number of subjects they are enrolled for:
# Print all students with a count of their courses. for ( name , subjects ) in students : print ( name , "takes" , len ( subjects ), "courses" )
Python approvingly responds with the post-obit output:
John takes two courses Vusi takes three courses Jess takes iv courses Sarah takes 4 courses Zuki takes 5 courses
Now we'd like to ask how many students are taking CompSci. This needs a counter, and for each pupil we demand a second loop that tests each of the subjects in plow:
# Count how many students are taking CompSci counter = 0 for ( name , subjects ) in students : for southward in subjects : # A nested loop! if southward == "CompSci" : counter += 1 impress ( "The number of students taking CompSci is" , counter )The number of students taking CompSci is 3
Y'all should ready up a list of your ain data that interests you — mayhap a list of your CDs, each containing a list of song titles on the CD, or a list of pic titles, each with a list of moving-picture show stars who acted in the movie. Y'all could and so inquire questions like "Which movies starred Angelina Jolie?"
7.23. Newton's method for finding square roots¶
Loops are oft used in programs that compute numerical results by starting with an approximate respond and iteratively improving it.
For example, earlier we had calculators or computers, people needed to calculate square roots manually. Newton used a particularly good method (there is some evidence that this method was known many years before). Suppose that yous want to know the square root of due north . If you start with nigh any approximation, you tin compute a ameliorate approximation (closer to the actual reply) with the post-obit formula:
better = ( approx + northward / approx ) / 2
Echo this calculation a few times using your reckoner. Tin can you lot come across why each iteration brings your estimate a trivial closer? I of the amazing backdrop of this particular algorithm is how quickly it converges to an authentic reply — a great advantage for doing it manually.
By using a loop and repeating this formula until the better approximation gets close enough to the previous one, we can write a office for computing the square root. (In fact, this is how your computer finds square roots — information technology may take a slightly different formula and method, but it is likewise based on repeatedly improving its guesses.)
This is an example of an indefinite iteration problem: we cannot predict in advance how many times we'll want to amend our guess — nosotros just want to go on getting closer and closer. Our stopping condition for the loop will be when our onetime guess and our improved guess are "close enough" to each other.
Ideally, we'd like the old and new estimate to be exactly equal to each other when nosotros stop. Merely exact equality is a tricky notion in reckoner arithmetics when real numbers are involved. Because existent numbers are not represented absolutely accurately (after all, a number similar pi or the square root of ii has an infinite number of decimal places because information technology is irrational), nosotros need to formulate the stopping test for the loop by asking "is a close enough to b"? This stopping condition tin can be coded similar this:
if abs ( a - b ) < 0.001 : # Brand this smaller for better accurateness interruption
Discover that we take the absolute value of the difference between a and b !
This problem is also a good instance of when a middle-leave loop is appropriate:
1 2 three four five 6 seven 8 nine 10 11 12 def sqrt ( n ): approx = northward / two.0 # Start with some or other approximate at the answer while Truthful : better = ( approx + due north / approx ) / two.0 if abs ( approx - amend ) < 0.001 : return better approx = better # Test cases print ( sqrt ( 25.0 )) impress ( sqrt ( 49.0 )) print ( sqrt ( 81.0 ))
The output is:
Come across if you can improve the approximations by changing the stopping condition. Also, step through the algorithm (perhaps by hand, using your calculator) to see how many iterations were needed earlier it accomplished this level of accuracy for sqrt(25) .
7.24. Algorithms¶
Newton'southward method is an instance of an algorithm: it is a mechanical procedure for solving a category of problems (in this case, calculating square roots).
Some kinds of knowledge are non algorithmic. For example, learning dates from history or your multiplication tables involves memorization of specific solutions.
Simply the techniques y'all learned for addition with carrying, subtraction with borrowing, and long division are all algorithms. Or if you are an gorging Sudoku puzzle solver, y'all might have some specific fix of steps that y'all always follow.
I of the characteristics of algorithms is that they do non require any intelligence to bear out. They are mechanical processes in which each step follows from the last according to a simple set of rules. And they're designed to solve a general class or category of problems, not but a single problem.
Understanding that hard issues can exist solved by step-by-step algorithmic processes (and having technology to execute these algorithms for u.s.) is one of the major breakthroughs that has had enormous benefits. So while the execution of the algorithm may be boring and may crave no intelligence, algorithmic or computational thinking — i.e. using algorithms and automation as the basis for approaching issues — is quickly transforming our society. Some claim that this shift towards algorithmic thinking and processes is going to take fifty-fifty more touch on on our society than the invention of the printing press. And the process of designing algorithms is interesting, intellectually challenging, and a central part of what we call programming.
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 practice information technology, just so far no 1 has been able to explicate how we do it, at least non in the form of a step-by-step mechanical algorithm.
7.25. Glossary¶
- algorithm
- A pace-past-step process for solving a category of bug.
- body
- The statements within a loop.
- breakpoint
- A place in your program code where program execution volition intermission (or break), allowing you to inspect the country of the program's variables, or single-step through individual statements, executing them one at a time.
- bump
- Developer slang. Synonym for increment.
- continue statement
- A statement that causes the rest of the electric current iteration of a loop to exist skipped. The flow of execution goes back to the top of the loop, evaluates the status, and if this is truthful the next iteration of the loop will brainstorm.
- counter
- A variable used to count something, usually initialized to nix and incremented in the body of a loop.
- cursor
- An invisible marker that keeps track of where the next character will be printed.
- decrement
- Subtract by ane.
- definite iteration
- A loop where we have an upper bound on the number of times the body will be executed. Definite iteration is usually best coded as a for loop.
- development plan
- A process for developing a programme. In this affiliate, nosotros demonstrated a style of evolution based on developing code to do simple, specific things so encapsulating and generalizing.
- encapsulate
- To divide a big complex program into components (similar functions) and isolate the components from each other (past using local variables, for example).
- escape sequence
- An escape character, \, followed by one or more printable characters used to designate a nonprintable character.
- generalize
- To replace something unnecessarily specific (similar a constant value) with something appropriately general (like a variable or parameter). Generalization makes lawmaking more versatile, more probable to be reused, and sometimes even easier to write.
- increment
- Both as a substantive and every bit a verb, increment means to increase by 1.
- space loop
- A loop in which the terminating condition is never satisfied.
- indefinite iteration
- A loop where we just demand to go along going until some condition is met. A while statement is used for this case.
- initialization (of a variable)
- To initialize a variable is to give it an initial value. Since in Python variables don't exist until they are assigned values, they are initialized when they are created. In other programming languages this is not the case, and variables can be created without beingness initialized, in which instance they have either default or garbage values.
- iteration
- Repeated execution of a set of programming statements.
- loop
- The construct that allows allows united states of america to repeatedly execute a argument or a group of statements until a terminating condition is satisfied.
- loop variable
- A variable used every bit part of the terminating status of a loop.
- meta-notation
- Extra symbols or notation that helps describe other note. Hither we introduced square brackets, ellipses, italics, and assuming as meta-notation to assistance draw optional, repeatable, substitutable and fixed parts of the Python syntax.
- centre-examination loop
- A loop that executes some of the trunk, so tests for the exit status, then may execute some more of the torso. Nosotros don't have a special Python construct for this instance, but can use while and suspension together.
- nested loop
- A loop inside the body of another loop.
- newline
- A special character that causes the cursor to movement to the showtime of the next line.
- post-test loop
- A loop that executes the body, then tests for the go out condition. Nosotros don't accept a special Python construct for this, only tin employ while and break together.
- pre-test loop
- A loop that tests earlier deciding whether the execute its body. for and while are both pre-test loops.
- single-stride
- A mode of interpreter execution where you are able to execute your program one step at a time, and inspect the consequences of that stride. Useful for debugging and building your internal mental model of what is going on.
- tab
- A special character that causes the cursor to move to the side by side tab cease on the current line.
- trichotomy
- Given any existent numbers a and b, exactly one of the post-obit relations holds: a < b, a > b, or a == b. Thus when yous tin can establish that ii of the relations are false, yous tin can assume the remaining one is true.
- trace
- To follow the flow of execution of a plan by paw, recording the alter of country of the variables and any output produced.
seven.26. Exercises¶
This chapter showed usa how to sum a list of items, and how to count items. The counting example also had an if statement that permit u.s. only count some selected items. In the previous chapter nosotros also showed a function find_first_2_letter_word that immune the states an "early get out" from inside a loop by using return when some condition occurred. We now too have break to go out a loop (merely not the enclosing role, and go along to abandon the current iteration of the loop without ending the loop.
Composition of list traversal, summing, counting, testing conditions and early exit is a rich collection of building blocks that tin be combined in powerful means to create many functions that are all slightly different.
The showtime six questions are typical functions you should exist able to write using only these building blocks.
-
Write a office to count how many odd numbers are in a listing.
-
Sum up all the even numbers in a list.
-
Sum upward all the negative numbers in a list.
-
Count how many words in a list have length five.
-
Sum all the elements in a list up to but not including the first even number. (Write your unit tests. What if there is no fifty-fifty number?)
-
Count how many words occur in a listing upwardly to and including the offset occurrence of the discussion "sam". (Write your unit tests for this case too. What if "sam" does not occur?)
-
Add a impress function to Newton's sqrt part that prints out ameliorate each fourth dimension it is calculated. Phone call your modified function with 25 as an argument and record the results.
-
Trace the execution of the concluding version of print_mult_table and effigy out how information technology works.
-
Write a function print_triangular_numbers(north) that prints out the outset northward triangular numbers. A call to print_triangular_numbers(5) would produce the following output:
(hint: use a web search to detect out what a triangular number is.)
-
Write a office, is_prime , which takes a single integer argument and returns True when the argument is a prime number and False otherwise. Add tests for cases like this:
test ( is_prime ( eleven )) test ( not is_prime ( 35 )) exam ( is_prime ( 19911121 ))
The last case could represent your birth date. Were you born on a prime day? In a class of 100 students, how many exercise you think would have prime birth dates?
-
Revisit the drunkard pirate problem from the exercises in affiliate 3. This fourth dimension, the drunk pirate makes a plow, and then takes some steps forward, and repeats this. Our social science student now records pairs of data: the angle of each turn, and the number of steps taken afterwards the plough. Her experimental data is [(160, 20), (-43, 10), (270, eight), (-43, 12)]. Employ a turtle to draw the path taken by our drunk friend.
-
Many interesting shapes can be drawn past the turtle by giving a list of pairs like nosotros did higher up, where the showtime item of the pair is the angle to plough, and the second item is the distance to move forward. Set up upwardly a list of pairs so that the turtle draws a house with a cross through the heart, equally testify here. This should be done without going over whatsoever of the lines / edges more than than once, and without lifting your pen.
-
Not all shapes like the one above tin be drawn without lifting your pen, or going over an edge more than once. Which of these can be drawn?
Now read Wikipedia's article(http://en.wikipedia.org/wiki/Eulerian_path) most Eulerian paths. Learn how to tell immediately by inspection whether it is possible to find a solution or not. If the path is possible, you'll likewise know where to put your pen to first drawing, and where you should stop upward!
-
What will num_digits(0) return? Modify information technology to render i for this example. Why does a call to num_digits(-24) result in an space loop? (hint: -1//10 evaluates to -1) Modify num_digits so that information technology works correctly with whatsoever integer value. Add these tests:
test ( num_digits ( 0 ) == ane ) test ( num_digits ( - 12345 ) == 5 )
-
Write a role num_even_digits(n) that counts the number of even digits in n . These tests should pass:
test ( num_even_digits ( 123456 ) == 3 ) test ( num_even_digits ( 2468 ) == 4 ) test ( num_even_digits ( 1357 ) == 0 ) examination ( num_even_digits ( 0 ) == one )
-
Write a function sum_of_squares(xs) that computes the sum of the squares of the numbers in the listing xs . For instance, sum_of_squares([two, three, 4]) should return 4+9+16 which is 29:
test ( sum_of_squares ([ two , 3 , 4 ]) == 29 ) test ( sum_of_squares ([ ]) == 0 ) exam ( sum_of_squares ([ 2 , - 3 , 4 ]) == 29 )
-
You and your friend are in a team to write a ii-player game, human against reckoner, such as Tic-Tac-Toe / Noughts and Crosses. Your friend will write the logic to play one circular of the game, while you will write the logic to permit many rounds of play, keep score, decide who plays, first, etc. The two of you lot negotiate on how the 2 parts of the program will fit together, and yous come upward with this simple scaffolding (which your friend will amend later):
i 2 iii iv 5 6 vii viii nine 10 11 12 xiii 14 15 16 17
# Your friend volition consummate this function def play_once ( human_plays_first ): """ Must play 1 round of the game. If the parameter is Truthful, the human being gets to play get-go, else the estimator gets to play showtime. When the round ends, the return value of the role is one of -one (man wins), 0 (game drawn), one (estimator wins). """ # This is all dummy scaffolding code correct at the moment... import random # See Modules affiliate ... rng = random . Random () # Choice a random result between -1 and 1. outcome = rng . randrange ( - 1 , ii ) print ( "Human plays beginning={0}, winner={i} " . format ( human_plays_first , effect )) return upshot
- Write the master program which repeatedly calls this function to play the game, and afterward each round it announces the event as "I win!", "You win!", or "Game drawn!". It then asks the histrion "Do yous want to play once more?" and either plays again, or says "Good day", and terminates.
- Go along score of how many wins each actor has had, and how many draws at that place have been. Subsequently each round of play, as well announce the scores.
- Add logic and so that the players accept turns to play first.
- Compute the per centum of wins for the man, out of all games played. Also denote this at the end of each circular.
- Draw a flowchart of your logic.
Source: https://openbookproject.net/thinkcs/python/english3e/iteration.html
0 Response to "Incorrect; Try Again; 4 Attempts Remaining Look Again at the Number of Iterations."
Post a Comment