How to Print Text Over Again 100 Times in Python 35
7. Iteration¶
Computers are often used to automate repetitive tasks. Repeating identical or similar tasks without making errors is something that computers practice well and people practise poorly.
Repeated execution of a set of statements is called iteration. Because iteration is then mutual, Python provides several language features to brand it easier. We've already seen the for argument in chapter 3. This the the form of iteration yous'll likely exist using almost often. But in this chapter nosotros've going to look at the while statement — some other way to have your program exercise iteration, useful in slightly unlike circumstances.
Earlier we practice that, let'south just review a few ideas...
seven.ane. Assignment¶
As we take mentioned previously, it is legal to make more 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).
airtime_remaining = xv print ( airtime_remaining ) airtime_remaining = 7 print ( airtime_remaining )
The output of this program is:
because the commencement fourth dimension airtime_remaining is printed, its value is 15, and the second time, its value is 7.
It is especially important to distinguish between an assignment argument and a Boolean expression that tests for equality. Because Python uses the equal token ( = ) for consignment, information technology is tempting to interpret a argument like a = b every bit a Boolean test. Unlike mathematics, it is non! Recollect that the Python token for the equality operator is == .
Note likewise that an equality exam is symmetric, simply assignment is non. For example, if a == 7 then 7 == a . Only in Python, the argument a = 7 is legal and 7 = a is not.
In Python, an consignment statement can make two variables equal, but because further assignments can change either of them, they don't have to stay that fashion:
a = 5 b = a # Afterward executing this line, a and b are now equal a = 3 # Later executing this line, a and b are no longer equal
The third line changes the value of a but does not change the value of b , and 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 too call up that variable was an unfortunae word to choose, and instead nosotros should have called them assignables. Python chooses to follow common terminology and token usage, also found in languages similar C, C++, Java, and C#, then we employ the tokens = for assignment, == for equality, and we talk of variables.
seven.2. Updating variables¶
When an assignment statement is executed, the right-hand side expression (i.due east. the expression that comes afterwards the assignment token) is evaluated kickoff. This produces a value. Then the assignment is made, so that the variable on the left-manus side now refers to the new value.
Ane of the most common forms of assignment is an update, where the new value of the variable depends on its old value. Deduct 40 cents from my airtime rest, or add one run to the scoreboard.
Line 2 ways go the electric current value of n, multiply information technology by three and add together one, and assign the reply to north, thus making n refer to the value. So afterwards executing the two lines above, n will point/refer to the integer 16.
If you try to become the value of a variable that has never been assigned to, you lot'll become an error:
>>> w = x + 1 Traceback (most recent call last): File "<interactive input>", line i, in NameError: proper name 'ten' is not divers
Before yous can update a variable, you have to initialize information technology to some starting value, normally with a unproblematic consignment:
runs_scored = 0 ... runs_scored = runs_scored + one
Line 3 — updating a variable past adding 1 to it — is very common. Information technology is called an increase of the variable; subtracting ane is called a decrement. Sometimes programmers also talk virtually bumping a variable, which ways the same as incrementing it by i.
7.3. The for loop revisited¶
Recall that the for loop processes each particular in a list. Each item in plow is (re-)assigned to the loop variable, and the trunk of the loop is executed. We saw this case in an earlier chapter:
for f in [ "Joe" , "Zoe" , "Brad" , "Angelina" , "Zuki" , "Thandi" , "Paris" ]: invitation = "Hi " + f + ". Please come to my party on Saturday!" print ( invitation )
Running through all the items in a listing is called traversing the list, or traversal.
Permit us write a function now to sum up all the elements in a list of numbers. Do this by hand start, and effort to isolate exactly what steps you lot take. Yous'll find you need to go along some "running total" of the sum and then far, either on a piece of paper, in your head, or in your calculator. Remembering things from one step to the side by side is precisely why we have variables in a plan: so we'll need some variable to remember the "running total". It should be initialized with a value of zero, and and then we need to traverse the items in the list. For each item, we'll want to update the running total by adding the next number to it.
1 2 three 4 5 half-dozen 7 eight 9 10 11 12 13 def mysum ( xs ): """ Sum all the numbers in the listing xs, and render the full. """ running_total = 0 for x in xs : running_total = running_total + x return running_total # Add tests like these to your test suite ... test ( mysum ([ 1 , 2 , 3 , 4 ]) == x ) test ( mysum ([ i.25 , 2.v , 1.75 ]) == 5.5 ) test ( mysum ([ ane , - 2 , three ]) == 2 ) test ( mysum ([ ]) == 0 ) test ( mysum ( range ( 11 )) == 55 ) # 11 is not included in the list.
7.4. The while statement¶
Hither is a fragment of code that demonstrates the use of the while statement:
1 2 3 4 5 six 7 8 9 10 xi 12 def sum_to ( north ): """ Render the sum of 1+2+3 ... n """ ss = 0 5 = i while 5 <= n : ss = ss + v v = 5 + 1 render ss # For your test suite test ( sum_to ( iv ) == 10 ) test ( sum_to ( 1000 ) == 500500 )
You can almost read the while statement as if it were English language. It means, while v is less than or equal to n , go along executing the body of the loop. Within the body, each time, increment 5 . When v passes n , return your accumulated sum.
More formally, here is precise flow of execution for a while statement:
- Evaluate the condition at line five, yielding a value which is either Faux or True .
- If the value is False , exit the while argument and keep execution at the next statement (line 8 in this example).
- If the value is True , execute each of the statements in the body (lines vi and 7) so go back to the while statement at line five.
The trunk consists of all of the statements indented below the while keyword.
Find that if the loop condition is False the outset time nosotros get loop, the statements in the torso of the loop are never executed.
The torso of the loop should modify the value of 1 or more than variables so that eventually the status becomes faux and the loop terminates. Otherwise the loop will echo forever, which is called an infinite loop. An endless source of entertainment for computer scientists is the ascertainment that the directions on shampoo, "lather, rinse, repeat", are an infinite loop.
In the instance here, we can evidence that the loop terminates because nosotros know that the value of northward is finite, and we can see that the value of 5 increments each time through the loop, then somewhen it volition have to exceed due north . In other cases, it is non so easy, even impossible in some cases, to tell if the loop volition ever terminate.
What yous will notice here is that the while loop is more than work for y'all — the programmer — than the equivalent for loop. When using a while loop 1 has to manage the loop variable yourself: give it an initial value, examination for completion, and so make sure you change something in the torso and then that the loop terminates. By comparison, hither is an equivalent function that uses for instead:
def sum_to ( n ): """ Render the sum of ane+two+3 ... n """ ss = 0 for v in range ( n + 1 ): ss = ss + 5 return ss
Notice the slightly tricky call to the range function — we had to add together i onto n , considering range generates its listing upwardly to merely excluding the value you lot requite it. It would be easy to make a programming error and overlook this, merely because we've fabricated the investment of writing some unit of measurement tests, our test suite would have caught our error.
And so why take two kinds of loop if for looks easier? This next instance shows a instance where we need the extra ability that we get from the while loop.
7.5. The Collatz 3n + 1 sequence¶
Allow's await at a simple sequence that has fascinated and foxed mathematicians for many years. They all the same cannot reply even quite uncomplicated questions about this.
The "computational rule" for creating the sequence is to start from some given north , and to generate the side by side term of the sequence from n , either past halving n , (whenever n is even), or else past multiplying it by three and calculation 1. The sequence terminates when n reaches one.
This Python function captures that algorithm:
def seq3np1 ( due north ): """ Print the 3n+1 sequence from n, terminating when it reaches 1. """ while northward != 1 : impress ( n , stop = ", " ) if n % two == 0 : # due north is even n = n // two else : # north is odd n = n * 3 + 1 print ( north , cease = ". \n " )
Find first that the print function on line 6 has an actress statement end=", " . This tells the print function to follow the printed string with whatever the developer chooses (in this instance, 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 same output line, with the numbers separated by commas. The call to print(n, end=".\n") at line 11 after the loop terminates volition then impress the final value of n followed by a flow and a newline graphic symbol. (You'll comprehend the \due north (newline character) in the next affiliate).
The condition for continuing with this loop is northward != 1 , so the loop will continue running until it reaches its termination status, (i.eastward. n == i ).
Each time through the loop, the program outputs the value of n so checks whether it is fifty-fifty or odd. If it is even, the value of n is divided by 2 using integer division. If it is odd, the value is replaced by due north * 3 + 1 . Here are some examples:
>>> seq3np1 ( 3 ) 3, x, five, xvi, eight, 4, two, i. >>> seq3np1 ( 19 ) xix, 58, 29, 88, 44, 22, 11, 34, 17, 52, 26, 13, forty, 20, ten, 5, 16, 8, 4, two, 1. >>> seq3np1 ( 21 ) 21, 64, 32, sixteen, 8, 4, 2, 1. >>> seq3np1 ( xvi ) 16, viii, 4, 2, 1. >>>
Since n sometimes increases and sometimes decreases, there is no obvious proof that northward will ever reach one, or that the plan terminates. For some detail values of n , we can prove termination. For example, if the starting value is a power of 2, and so the value of n will be even each time through the loop until it reaches ane. The previous example ends with such a sequence, starting with 16.
See if you lot can find a small starting number that needs more than a hundred steps before it terminates.
Particular values bated, the interesting question was first posed by a German mathematician called Lothar Collatz: the Collatz conjecture (likewise known as the 3n + 1 conjecture), is that this sequence terminates for all positive values of n . So far, no 1 has been able to bear witness it or disprove information technology! (A conjecture is a statement that might be truthful, merely nobody knows for sure.)
Think carefully nigh what would be needed for a proof or disproof of the conjecture "All positive integers volition somewhen converge to i using the Collatz rules". With fast computers we have been able to test every integer up to very large values, and so far, they have all eventually ended up at 1. But who knows? Perhaps there is some equally-yet untested number which does not reduce to 1.
Yous'll notice that if y'all don't stop when you accomplish 1, the sequence gets into its ain cyclic loop: 1, 4, two, i, 4, ii, i, 4 ... So one possibility is that in that location might be other cycles that we but haven't plant yet.
Wikipedia has an informative commodity almost the Collatz conjecture. The sequence besides goes under other names (Hailstone sequence, Wonderous numbers, etc.), and you'll discover out simply how many integers accept already been tested past calculator, and establish to converge!
Choosing between for and while
Use a for loop if y'all know, before you start looping, the maximum number of times that you'll demand to execute the body. For example, if y'all're traversing a list of elements, you know that the maximum number of loop iterations y'all can perchance need is "all the elements in the list". Or if you need to print the 12 times table, we know right away how many times the loop will need to run.
So any problem similar "iterate this weather model for 1000 cycles", or "search this list of words", "discover all prime numbers upward to 10000" advise that a for loop is best.
By contrast, if yous are required to repeat some computation until some condition is met, and you cannot calculate in advance when (of if) this will happen, as we did in this 3n + one problem, you lot'll need a while loop.
Nosotros call the get-go 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 — we cannot even institute an upper bound!
7.half dozen. Tracing a program¶
To write effective computer programs, and to build a expert conceptual model of program execution, a programmer needs to develop the ability to trace the execution of a estimator program. Tracing involves condign the computer and following the flow of execution through a sample program run, recording the country of all variables and any output the plan generates after each instruction is executed.
To sympathise this procedure, let'south trace the call to seq3np1(3) from the previous section. At the commencement of the trace, we have a variable, n (the parameter), with an initial value of 3. Since 3 is not equal to 1, the while loop body is executed. 3 is printed and 3 % 2 == 0 is evaluated. Since it evaluates to False , the else branch is executed and 3 * 3 + i is evaluated and assigned to due north .
To continue runway of all this as you hand trace a program, brand a column heading on a piece of newspaper for each variable created as the programme runs and another one for output. Our trace so far would await something like this:
north output printed so far -- --------------------- 3 3, 10
Since 10 != 1 evaluates to Truthful , the loop trunk is once again executed, and 10 is printed. x % 2 == 0 is true, and then the if co-operative is executed and north becomes v. By the finish of the trace we have:
due north output printed so far -- --------------------- three 3, 10 iii, x, five 3, 10, five, xvi three, 10, 5, xvi, 8 iii, 10, v, 16, viii, 4 three, 10, 5, 16, 8, iv, 2 3, 10, five, xvi, 8, 4, ii, one iii, x, five, 16, eight, 4, 2, one.
Tracing can be a bit tedious and error prone (that'due south why nosotros go computers to do this stuff in the offset place!), but it is an essential skill for a developer to have. From this trace we can learn a lot about the fashion our code works. We can observe that as before long as n becomes a ability of 2, for instance, the program will require log2(n) executions of the loop torso to complete. Nosotros tin likewise see that the terminal one will not be printed as output within the torso of the loop, which is why nosotros put the special print role at the end.
Tracing a program is, of course, related to unmarried-stepping through your lawmaking and being able to inspect the variables. Using the computer to unmarried-stride for yous is less error prone and more convenient. Also, as your programs get more complex, they might execute many millions of steps before they go to the lawmaking that you're really interested in, then manual tracing becomes incommunicable. Being able to set a breakpoint where you need one is far more powerful. And so we strongly encourage you lot to invest time in learning using to use your programming environment (PyScripter, in these notes) to total event.
At that place are also some great visualization tools condign bachelor to aid you lot trace and understand pocket-sized fragments of Python code. The one we recommend is at http://netserv.ict.ru.air conditioning.za/python3_viz
We've cautioned confronting chatterbox functions, but used them hither. As we learn a bit more than Python, we'll be able to bear witness you how to generate a list of values to hold the sequence, rather than having the function print them. Doing this would remove the demand to have all these pesky print functions in the middle of our logic, and will brand the function more than useful.
seven.7. Counting digits¶
The following office counts the number of decimal digits in a positive integer:
def num_digits ( n ): count = 0 while n != 0 : count = count + i n = n // 10 return count
A call to print(num_digits(710)) will print three . Trace the execution of this part phone call (maybe using the unmarried step function in PyScripter, or the Python visualizer, or on some paper) to convince yourself that it works.
This function demonstrates an important pattern of computation chosen a counter. The variable count is initialized to 0 and and so incremented each time the loop body is executed. When the loop exits, count contains the result — the total number of times the loop body was executed, which is the same every bit the number of digits.
If we wanted to only count digits that are either 0 or 5, adding a conditional earlier incrementing the counter volition do the trick:
def num_zero_and_five_digits ( northward ): count = 0 while n > 0 : digit = n % 10 if digit == 0 or digit == 5 : count = count + 1 north = n // 10 render count
Confirm that exam(num_zero_and_five_digits(1055030250) == 7) passes.
Notice, yet, that test(num_digits(0) == 1) fails. Explain why. Do yous think this is a problems in the code, or a bug in the specifications, or our expectations, or the tests?
vii.8. Abbreviated consignment¶
Incrementing a variable is and then common that Python provides an abbreviated syntax for information technology:
>>> count = 0 >>> count += 1 >>> count 1 >>> count += 1 >>> count 2
count += 1 is an abreviation for count = count + one . We pronounce the operator equally "plus-equals". The increment value does not have to be 1:
>>> n = 2 >>> north += 5 >>> northward 7
There are similar abbreviations for -= , *= , /= , //= and %= :
>>> due north = two >>> due north *= five >>> n 10 >>> northward -= 4 >>> n half dozen >>> n //= 2 >>> n 3 >>> n %= 2 >>> due north ane
vii.ten. Tables¶
I of the things loops are good for is generating tables. Before computers were readily available, people had to summate logarithms, sines and cosines, and other mathematical functions past hand. To make that easier, mathematics books contained long tables listing the values of these functions. Creating the tables was dull and ho-hum, and they tended to be total of errors.
When computers appeared on the scene, one of the initial reactions was, "This is dandy! We can use the computers to generate the tables, so at that place will be no errors." That turned out to be true (mostly) but shortsighted. Soon thereafter, computers and calculators were and then pervasive that the tables became obsolete.
Well, virtually. For some operations, computers employ tables of values to get an estimate respond and so perform computations to ameliorate the approximation. In some cases, there have been errors in the underlying tables, virtually famously in the table the Intel Pentium processor scrap used to perform floating-bespeak division.
Although a log table is non as useful as information technology one time was, it nevertheless makes a good case of iteration. The following program outputs a sequence of values in the left cavalcade and 2 raised to the ability of that value in the right cavalcade:
for x in range ( 13 ): # Generate numbers 0 to 12 print ( x , " \t " , two ** ten )
The string "\t" represents a tab grapheme. The backslash character in "\t" indicates the beginning of an escape sequence. Escape sequences are used to stand for invisible characters similar tabs and newlines. The sequence \due north represents a newline.
An escape sequence tin announced anywhere in a string; in this example, the tab escape sequence is the merely thing in the string. How do yous retrieve you stand for a backslash in a string?
As characters and strings are displayed on the screen, an invisible mark called the cursor keeps track of where the next character will get. After a impress function, the cursor normally goes to the beginning of the adjacent line.
The tab grapheme shifts the cursor to the right until it reaches ane of the tab stops. Tabs are useful for making columns of text line upward, every bit in the output of the previous programme:
0 1 1 2 2 4 three eight four 16 5 32 6 64 seven 128 viii 256 9 512 x 1024 11 2048 12 4096
Because of the tab characters between the columns, the position of the second cavalcade does not depend on the number of digits in the beginning cavalcade.
7.11. Two-dimensional tables¶
A ii-dimensional table is a table where you lot read the value at the intersection of a row and a column. A multiplication table is a good case. Allow'southward say you want to print a multiplication table for the values from 1 to 6.
A skilful way to start is to write a loop that prints the multiples of ii, all on one line:
for i in range ( 1 , seven ): print ( 2 * i , end = " " ) print ()
Here we've used the range role, simply fabricated it beginning its sequence at ane. As the loop executes, the value of i changes from ane to half-dozen. When all the elements of the range have been assigned to i , the loop terminates. Each time through the loop, it displays the value of two * i , followed by three spaces.
Again, the extra terminate=" " argument in the print part suppresses the newline, and uses iii spaces instead. After the loop completes, the telephone call to impress at line 3 finishes the electric current line, and starts a new line.
The output of the program is:
So far, so skillful. The next step is to encapsulate and generalize.
7.12. Encapsulation and generalization¶
Encapsulation is the process of wrapping a piece of code in a function, allowing y'all to take advantage of all the things functions are skilful for. You lot accept already seen some examples of encapsulation, including is_divisible in a previous chapter.
Generalization ways taking something specific, such as printing the multiples of 2, and making it more general, such equally printing the multiples of any integer.
This function encapsulates the previous loop and generalizes information technology to print multiples of n :
def print_multiples ( n ): for i in range ( 1 , 7 ): print ( northward * i , stop = " " ) print ()
To encapsulate, all nosotros had to do was add the get-go line, which declares the name of the function and the parameter list. To generalize, all we had to practise was replace the value ii with the parameter due north .
If nosotros call this office with the argument 2, nosotros get the same output every bit earlier. With the argument three, the output is:
With the statement 4, the output is:
By at present you tin can probably guess how to print a multiplication table — by calling print_multiples repeatedly with different arguments. In fact, nosotros can use another loop:
for i in range ( ane , seven ): print_multiples ( i )
Notice how similar this loop is to the 1 inside print_multiples . All we did was replace the impress office with a function call.
The output of this program is a multiplication table:
1 2 3 4 5 half dozen 2 four six 8 10 12 3 6 nine 12 15 18 four 8 12 sixteen 20 24 v ten xv 20 25 30 six 12 eighteen 24 thirty 36
7.13. More encapsulation¶
To demonstrate encapsulation again, let'south accept the code from the concluding section and wrap it up in a function:
def print_mult_table (): for i in range ( 1 , 7 ): print_multiples ( i )
This procedure is a common development programme. We develop code by writing lines of code exterior any function, or typing them in to the interpreter. When we get the code working, we extract it and wrap it upwards in a function.
This development plan is especially useful if you don't know how to split up the program into functions when yous start writing. This approach lets you pattern as yous go along.
seven.14. Local variables¶
You might be wondering how nosotros can use the same variable, i , in both print_multiples and print_mult_table . Doesn't information technology crusade issues when ane of the functions changes the value of the variable?
The reply is no, because the i in print_multiples and the i in print_mult_table are not the same variable.
Variables created within a function definition are local; you can't access a local variable from outside its habitation function. That means yous are free to have multiple variables with the same name every bit long as they are not in the same function.
Python examines all the statements in a function — if any of them assign a value to a variable, that is the inkling that Python uses to make the variable a local variable.
The stack diagram for this program shows that the two variables named i are not the aforementioned variable. They tin can refer to dissimilar values, and irresolute one does not affect the other.
The value of i in print_mult_table goes from 1 to half dozen. In the diagram it happens to be 3. The side by side time through the loop it volition be 4. Each time through the loop, print_mult_table calls print_multiples with the electric current value of i as an argument. That value gets assigned to the parameter n .
Inside print_multiples , the value of i goes from i to 6. In the diagram, it happens to be two. Irresolute this variable has no effect on the value of i in print_mult_table .
It is mutual and perfectly legal to accept different local variables with the same name. In particular, names like i and j are used oft as loop variables. If you avoid using them in one function just because y'all used them somewhere else, y'all will probably make the program harder to read.
The visualizer at http://netserv.ict.ru.ac.za/python3_viz/ shows very clearly how the two variables i are singled-out variables, and how they have independent values.
7.xv. The break argument¶
The break statement is used to immediately leave the body of its loop. The side by side statement to be executed is the first i later on the body:
for i in [ 12 , 16 , 17 , 24 , 29 ]: if i % two == ane : # If the number is odd break # ... immediately exit the loop print ( i ) print ( "washed" )
This prints:
The pre-exam loop — standard loop behaviour
for and while loops practise their tests at the starting time, before executing whatsoever part of the body. They're called pre-exam loops, considering the examination happens before (pre) the body. suspension and return are our tools for adapting this standard behaviour.
7.16. Other flavours of loops¶
Sometimes nosotros'd like to have the center-examination loop with the go out test in the eye of the body, rather than at the beginning or at the stop. Or a post-examination loop that puts its exit examination as the terminal thing in the torso. Other languages take dissimilar syntax and keywords for these unlike flavours, only Python just uses a combination of while and if condition: break to get the job done.
A typical example is a problem where the user has to input numbers to be summed. To indicate that there are no more than inputs, the user enters a special value, often the value -1, or the empty string. This needs a middle-go out loop design: input the side by side number, then test whether to exit, or else process the number:
The middle-test loop flowchart
total = 0 while True : response = input ( "Enter the next number. (Leave bare to end)" ) if response == "" : suspension full += int ( response ) print ( "The full of the numbers you lot entered is " , total )
Convince yourself that this fits the heart-exit loop flowchart: line three does some useful piece of work, lines 4 and 5 can go out the loop, and if they don't line 6 does more useful work earlier the adjacent iteration starts.
The while bool-expr: uses the Boolean expression to determine whether to iterate over again. True is a lilliputian Boolean expression, so while Truthful: means always do the loop body again. This is a language idiom — a convention that most programmers volition recognize immediately. Since the expression on line 2 will never terminate the loop, (it is a dummy examination) the developer must arrange to interruption (or render) out of the loop body elsewhere, in some other fashion (i.e. in lines four and 5 in this sample). A clever compiler or interpreter volition sympathize that line 2 is a fake test that must always succeed, so it won't even generate a examination, and our flowchart never even put the diamond-shape dummy test box at the top of the loop!
Similarly, by merely moving the if condition: break to the cease of the loop body we create a blueprint for a post-test loop. Mail service-test loops are used when you want to be sure that the loop torso always executes at least once (because the kickoff test only happens at the cease of the execution of the offset loop trunk). This is useful, for example, if we want to play an interactive game against the user — nosotros always desire to play at least one game:
while Truthful : play_the_game_once () response = input ( "Play once more? (yeah or no)" ) if response != "aye" : break print ( "Goodbye!" )
Hint: Think most where you want the exit examination to happen
In one case you've recognized that you lot need a loop to echo something, think almost its terminating status — when volition I want to cease iterating? So effigy out whether you lot need to do the examination earlier starting the first (and every other) iteration, or at the terminate of the first (and every other) iteration, or perhaps in the middle of each iteration. Interactive programs that require input from the user or read from files often need to exit their loops in the center or at the terminate of an iteration, when it becomes clear that at that place is no more than information to process, or the user doesn't desire to play our game anymore.
7.17. An example¶
The post-obit programme implements a simple guessing game:
1 2 3 4 5 6 7 8 nine 10 11 12 13 14 15 sixteen 17 18 import random # Nosotros cover random numbers in the rng = random . Random () # modules chapter, then peek alee. number = rng . randrange ( 1 , thou ) # Become random number between [ane and grand). guesses = 0 msg = "" while True : approximate = int ( input ( msg + " \north Guess my number between 1 and grand: " )) guesses += 1 if gauge > number : msg += str ( guess ) + " is too high. \northward " elif estimate < number : msg += str ( guess ) + " is besides low. \n " else : break input ( " \n\n Great, you lot got it in {0} guesses! \north\n " . format ( guesses ))
This plan makes employ of the mathematical police force of trichotomy (given real 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 function, only we don't do anything with the upshot, not fifty-fifty assign it to a variable. This is legal in Python. Here it has the event of popping upwardly the input dialog window and waiting for the user to reply before the programme terminates. Programmers frequently utilise the pull a fast one on of doing some extra input at the end of a script, merely to go along the window open.
As well find the utilize of the msg variable, initially an empty string, on lines 6, 12 and 14. Each time through the loop nosotros extend the bulletin being displayed: this allows us to brandish the plan's feedback correct at the aforementioned identify equally nosotros're asking for the side by side approximate.
7.18. The go along statement¶
This is a command flow statement that causes the plan to immediately skip the processing of the rest of the body of the loop, for the current iteration. But the loop yet carries on running for its remaining iterations:
for i in [ 12 , 16 , 17 , 24 , 29 , 30 ]: if i % two == 1 : # If the number is odd continue # Don't process it print ( i ) impress ( "done" )
This prints:
7.19. More generalization¶
As another example of generalization, imagine you wanted a programme that would print a multiplication table of any size, not merely the half-dozen-by-6 table. Y'all could add together a parameter to print_mult_table :
def print_mult_table ( high ): for i in range ( i , high + 1 ): print_multiples ( i )
We replaced the value 7 with the expression loftier+1 . If nosotros call print_mult_table with the argument vii, it displays:
1 2 3 4 5 6 2 iv half dozen 8 ten 12 3 6 9 12 15 18 iv 8 12 xvi 20 24 5 10 fifteen xx 25 thirty half dozen 12 eighteen 24 xxx 36 7 14 21 28 35 42
This is fine, except that we probably desire the tabular array to be square — with the aforementioned number of rows and columns. To do that, we add another parameter to print_multiples to specify how many columns the table should have.
Just to be abrasive, we call this parameter high , demonstrating that different functions can take parameters with the same name (simply like local variables). Here's the whole plan:
def print_multiples ( due north , loftier ): for i in range ( 1 , high + 1 ): print ( due north * i , terminate = " " ) impress () def print_mult_table ( loftier ): for i in range ( i , high + 1 ): print_multiples ( i , high )
Find that when we added a new parameter, we had to change the first line of the function (the office heading), and we also had to alter the identify where the part is called in print_mult_table .
At present, when we call print_mult_table(7) :
ane 2 3 4 5 6 vii 2 4 half-dozen 8 10 12 14 3 six 9 12 15 eighteen 21 4 8 12 16 xx 24 28 5 10 15 20 25 xxx 35 half dozen 12 18 24 thirty 36 42 vii 14 21 28 35 42 49
When you generalize a function appropriately, you often become a program with capabilities yous didn't programme. For example, you might notice that, because ab = ba, all the entries in the table appear twice. You could salvage ink by printing only half the tabular array. To do that, you only have to alter one line of print_mult_table . Change
print_multiples ( i , loftier + 1 )
to
and you go:
ane ii 4 3 vi ix 4 8 12 16 v 10 15 20 25 vi 12 18 24 xxx 36 7 14 21 28 35 42 49
7.20. Functions¶
A few times now, nosotros have mentioned all the things functions are good for. Past now, you might be wondering what exactly those things are. Here are some of them:
- Capturing your mental chunking. Breaking your circuitous tasks into sub-tasks, and giving the sub-tasks a meaningful name is a powerful mental technique. Look back at the example that illustrated the post-examination loop: nosotros assumed that we had a office chosen play_the_game_once . This chunking immune us to put aside the details of the particular game — is it a card game, or noughts and crosses, or a role playing game — and merely focus on one isolated role of our program logic — letting the role player choose whether they desire to play again.
- Dividing a long program into functions allows you to separate parts of the plan, debug them in isolation, and then compose them into a whole.
- Functions facilitate the apply of iteration.
- Well-designed functions are often useful for many programs. Once you write and debug i, you tin reuse it.
vii.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 trivial, and show a more advanced way of representing our data. Making a pair of things in Python is as simple every bit putting them into parentheses, like this:
year_born = ( "Paris Hilton" , 1981 )
We can put many pairs into a list of pairs:
celebs = [( "Brad Pitt" , 1963 ), ( "Jack Nicholson" , 1937 ), ( "Justin Bieber" , 1994 )]
Here is a quick sample of things we can do with structured data like this. First, print all the celebs:
print ( celebs ) print ( len ( celebs ))[("Brad Pitt", 1963), ("Jack Nicholson", 1937), ("Justin Bieber", 1994)] 3
Find that the celebs listing has just iii elements, each of them pairs.
Now we impress the names of those celebrities born earlier 1980:
for ( nm , year ) in celebs : if year < 1980 : impress ( nm )
This demonstrates something we have non seen yet in the for loop: instead of using a unmarried loop command variable, we've used a pair of variable names, (nm, yr) , instead. The loop is executed three times — once for each pair in the listing, 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 fifty-fifty more audacious list of structured data. In this case, we have a list of students. Each student has a proper 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" , "Accounting" , "Economics" , "Management" ]), ( "Sarah" , [ "InfSys" , "Accounting" , "Economics" , "CommLaw" ]), ( "Zuki" , [ "Folklore" , "Economics" , "Police" , "Stats" , "Music" ])]
Hither we've assigned a list of five elements to the variable students . Let's print out each student name, and the number of subjects they are enrolled for:
# Impress 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 2 courses Vusi takes 3 courses Jess takes 4 courses Sarah takes 4 courses Zuki takes v courses
Now nosotros'd similar to inquire how many students are taking CompSci. This needs a counter, and for each student we need a second loop that tests each of the subjects in turn:
# Count how many students are taking CompSci counter = 0 for ( proper name , subjects ) in students : for s in subjects : # A nested loop! if s == "CompSci" : counter += 1 print ( "The number of students taking CompSci is" , counter )The number of students taking CompSci is 3
You should gear up a list of your own data that interests you — peradventure a list of your CDs, each containing a listing of song titles on the CD, or a list of moving picture titles, each with a list of motion picture stars who acted in the motion-picture show. You could then inquire questions like "Which movies starred Angelina Jolie?"
7.23. Newton'south method for finding square roots¶
Loops are often used in programs that compute numerical results by starting with an judge answer and iteratively improving information technology.
For instance, before we had calculators or computers, people needed to calculate square roots manually. Newton used a specially good method (at that place is some bear witness that this method was known many years earlier). Suppose that you want to know the square root of n . If yous commencement with nearly any approximation, yous can compute a ameliorate approximation (closer to the actual answer) with the post-obit formula:
better = ( approx + due north / approx ) / 2
Repeat this calculation a few times using your figurer. Can y'all see why each iteration brings your estimate a little closer? One of the amazing properties of this item algorithm is how quickly it converges to an accurate answer — a bang-up advantage for doing it manually.
By using a loop and repeating this formula until the amend approximation gets close enough to the previous one, we can write a function for computing the square root. (In fact, this is how your calculator finds foursquare roots — it may accept a slightly dissimilar formula and method, but information technology is as well 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 desire to improve our guess — we just desire to keep getting closer and closer. Our stopping condition for the loop will be when our old guess and our improved guess are "close enough" to each other.
Ideally, we'd similar the old and new guess to exist exactly equal to each other when we terminate. Only exact equality is a tricky notion in computer 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 two has an space number of decimal places because information technology is irrational), nosotros need to formulate the stopping test for the loop by asking "is a close plenty to b"? This stopping status can be coded like this:
if abs ( a - b ) < 0.001 : # Brand this smaller for better accuracy break
Notice that we take the accented value of the departure between a and b !
This problem is likewise a good example of when a center-exit loop is advisable:
1 2 3 iv v 6 7 8 ix 10 11 12 def sqrt ( n ): approx = n / 2.0 # Start with some or other guess at the reply while True : better = ( approx + north / approx ) / two.0 if abs ( approx - improve ) < 0.001 : return amend approx = ameliorate # Test cases print ( sqrt ( 25.0 )) print ( sqrt ( 49.0 )) impress ( sqrt ( 81.0 ))
The output is:
Run across if yous tin improve the approximations by changing the stopping status. Also, step through the algorithm (peradventure past hand, using your calculator) to see how many iterations were needed before it achieved this level of accuracy for sqrt(25) .
7.24. Algorithms¶
Newton's method is an example of an algorithm: information technology is a mechanical process for solving a category of issues (in this case, computing square roots).
Some kinds of knowledge are not algorithmic. For example, learning dates from history or your multiplication tables involves memorization of specific solutions.
But the techniques you lot learned for addition with conveying, subtraction with borrowing, and long partitioning are all algorithms. Or if you are an avid Sudoku puzzle solver, you might have some specific prepare of steps that you lot always follow.
One of the characteristics of algorithms is that they practice non require whatever intelligence to carry out. They are mechanical processes in which each step follows from the concluding co-ordinate to a simple set of rules. And they're designed to solve a general class or category of problems, non just a single problem.
Understanding that hard problems can exist solved by stride-by-step algorithmic processes (and having engineering to execute these algorithms for us) is one of the major breakthroughs that has had enormous benefits. So while the execution of the algorithm may be wearisome and may require no intelligence, algorithmic or computational thinking — i.eastward. using algorithms and automation every bit the footing for approaching bug — is speedily transforming our lodge. Some claim that this shift towards algorithmic thinking and processes is going to have even more than impact on our lodge than the invention of the press press. And the process of designing algorithms is interesting, intellectually challenging, and a central role of what nosotros telephone call programming.
Some of the things that people practise naturally, without difficulty or witting thought, are the hardest to limited algorithmically. Understanding tongue is a proficient example. Nosotros all practice it, just then far no ane has been able to explain how nosotros do it, at to the lowest degree non in the class of a step-past-stride mechanical algorithm.
7.25. Glossary¶
- algorithm
- A step-past-step process for solving a category of problems.
- trunk
- The statements inside a loop.
- breakpoint
- A identify in your program lawmaking where program execution volition interruption (or break), allowing you to inspect the country of the program'south variables, or single-stride through individual statements, executing them one at a time.
- crash-land
- Programmer slang. Synonym for increment.
- go along argument
- A statement that causes the remainder of the electric current iteration of a loop to be skipped. The flow of execution goes back to the top of the loop, evaluates the status, and if this is true the next iteration of the loop will brainstorm.
- counter
- A variable used to count something, usually initialized to zero and incremented in the body of a loop.
- cursor
- An invisible marker that keeps rail of where the next character will be printed.
- decrement
- Decrease by one.
- definite iteration
- A loop where nosotros have an upper spring on the number of times the body will be executed. Definite iteration is usually all-time coded as a for loop.
- development programme
- A process for developing a program. In this affiliate, we demonstrated a style of evolution based on developing lawmaking to do simple, specific things and then encapsulating and generalizing.
- encapsulate
- To divide a large complex plan into components (like functions) and isolate the components from each other (by using local variables, for example).
- escape sequence
- An escape character, \, followed past i or more printable characters used to designate a nonprintable character.
- generalize
- To replace something unnecessarily specific (like a constant value) with something accordingly full general (like a variable or parameter). Generalization makes code more versatile, more probable to be reused, and sometimes even easier to write.
- increment
- Both equally a noun and as a verb, increase means to increase by 1.
- space loop
- A loop in which the terminating condition is never satisfied.
- indefinite iteration
- A loop where nosotros simply need to keep going until some condition is met. A while argument 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 being initialized, in which case they take either default or garbage values.
- iteration
- Repeated execution of a set of programming statements.
- loop
- The construct that allows allows us to repeatedly execute a argument or a group of statements until a terminating condition is satisfied.
- loop variable
- A variable used as part of the terminating condition of a loop.
- meta-notation
- Extra symbols or notation that helps describe other annotation. Here we introduced square brackets, ellipses, italics, and bold as meta-notation to help describe optional, repeatable, substitutable and fixed parts of the Python syntax.
- middle-test loop
- A loop that executes some of the torso, then tests for the exit condition, then may execute some more of the body. We don't have a special Python construct for this case, but can use while and break together.
- nested loop
- A loop inside the body of some other loop.
- newline
- A special character that causes the cursor to move to the beginning of the next line.
- post-examination loop
- A loop that executes the body, then tests for the go out condition. We don't have a special Python construct for this, only tin can use while and break together.
- pre-test loop
- A loop that tests earlier deciding whether the execute its body. for and while are both pre-exam loops.
- single-step
- A manner of interpreter execution where y'all are able to execute your programme 1 step at a time, and inspect the consequences of that step. Useful for debugging and building your internal mental model of what is going on.
- tab
- A special character that causes the cursor to motion to the next tab stop on the current line.
- trichotomy
- Given whatsoever real numbers a and b, exactly i of the following relations holds: a < b, a > b, or a == b. Thus when you tin can establish that two of the relations are simulated, you can assume the remaining one is truthful.
- trace
- To follow the flow of execution of a program by paw, recording the change of state of the variables and any output produced.
7.26. Exercises¶
This affiliate showed us how to sum a list of items, and how to count items. The counting case also had an if statement that let usa only count some selected items. In the previous chapter we also showed a function find_first_2_letter_word that allowed us an "early on exit" from within a loop past using return when some condition occurred. Nosotros at present also take interruption to exit a loop (but not the enclosing function, and proceed to abandon the current iteration of the loop without catastrophe the loop.
Composition of list traversal, summing, counting, testing weather condition and early exit is a rich collection of building blocks that tin can be combined in powerful ways to create many functions that are all slightly different.
The first 6 questions are typical functions you should be able to write using merely these building blocks.
-
Write a function to count how many odd numbers are in a listing.
-
Sum up all the fifty-fifty numbers in a listing.
-
Sum upwardly all the negative numbers in a list.
-
Count how many words in a list accept length v.
-
Sum all the elements in a list upwardly to merely not including the first even number. (Write your unit tests. What if there is no even number?)
-
Count how many words occur in a list upward to and including the beginning occurrence of the word "sam". (Write your unit tests for this case also. What if "sam" does non occur?)
-
Add together a print function to Newton's sqrt function that prints out better each time it is calculated. Call your modified function with 25 as an argument and record the results.
-
Trace the execution of the last version of print_mult_table and figure out how it works.
-
Write a office print_triangular_numbers(due north) that prints out the start n triangular numbers. A telephone call to print_triangular_numbers(5) would produce the following output:
(hint: use a spider web search to find out what a triangular number is.)
-
Write a function, is_prime , which takes a unmarried integer argument and returns Truthful when the statement is a prime number number and Simulated otherwise. Add tests for cases like this:
test ( is_prime ( 11 )) test ( non is_prime ( 35 )) test ( is_prime ( 19911121 ))
The last case could represent your birth date. Were yous born on a prime day? In a course of 100 students, how many do yous think would have prime nascency dates?
-
Revisit the drunk pirate trouble from the exercises in chapter 3. This time, the drunk pirate makes a plough, and so takes some steps forward, and repeats this. Our social scientific discipline educatee at present records pairs of data: the angle of each plough, and the number of steps taken after the turn. Her experimental data is [(160, 20), (-43, 10), (270, 8), (-43, 12)]. Use a turtle to draw the path taken past our drunk friend.
-
Many interesting shapes can be drawn by the turtle by giving a listing of pairs like we did in a higher place, where the first particular of the pair is the bending to plow, and the 2nd item is the distance to move forward. Fix a list of pairs so that the turtle draws a business firm with a cross through the centre, as show here. This should be done without going over any of the lines / edges more than than once, and without lifting your pen.
-
Not all shapes like the one above tin can exist fatigued without lifting your pen, or going over an edge more than than once. Which of these tin can be drawn?
Now read Wikipedia'due south article(http://en.wikipedia.org/wiki/Eulerian_path) about Eulerian paths. Learn how to tell immediately past inspection whether information technology is possible to observe a solution or not. If the path is possible, you'll also know where to put your pen to first drawing, and where you should end upwards!
-
What will num_digits(0) render? Alter it to return one for this case. Why does a call to num_digits(-24) result in an infinite loop? (hint: -one//10 evaluates to -ane) Change num_digits so that it works correctly with any integer value. Add these tests:
test ( num_digits ( 0 ) == 1 ) test ( num_digits ( - 12345 ) == five )
-
Write a office num_even_digits(n) that counts the number of fifty-fifty digits in n . These tests should pass:
test ( num_even_digits ( 123456 ) == three ) test ( num_even_digits ( 2468 ) == iv ) exam ( num_even_digits ( 1357 ) == 0 ) test ( num_even_digits ( 0 ) == 1 )
-
Write a role sum_of_squares(xs) that computes the sum of the squares of the numbers in the list xs . For example, sum_of_squares([2, 3, 4]) should return four+9+16 which is 29:
test ( sum_of_squares ([ ii , three , iv ]) == 29 ) examination ( sum_of_squares ([ ]) == 0 ) test ( sum_of_squares ([ 2 , - three , 4 ]) == 29 )
-
Yous and your friend are in a squad to write a two-thespian game, human against reckoner, such as Tic-Tac-Toe / Noughts and Crosses. Your friend will write the logic to play one round of the game, while you will write the logic to allow many rounds of play, go along score, determine who plays, commencement, etc. The 2 of you negotiate on how the two parts of the program will fit together, and yous come up with this simple scaffolding (which your friend volition improve later):
1 2 iii 4 5 6 7 8 9 x 11 12 xiii 14 15 sixteen 17
# Your friend will complete this function def play_once ( human_plays_first ): """ Must play one round of the game. If the parameter is True, the human gets to play first, else the figurer gets to play first. When the round ends, the return value of the function is one of -1 (human wins), 0 (game drawn), ane (reckoner wins). """ # This is all dummy scaffolding code right at the moment... import random # Come across Modules affiliate ... rng = random . Random () # Pick a random result between -one and 1. outcome = rng . randrange ( - one , 2 ) impress ( "Human plays first={0}, winner={ane} " . format ( human_plays_first , result )) return result
- Write the principal program which repeatedly calls this part to play the game, and later on each round it announces the outcome as "I win!", "You win!", or "Game drawn!". It then asks the player "Do you lot want to play again?" and either plays again, or says "Goodbye", and terminates.
- Keep score of how many wins each player has had, and how many draws at that place have been. Later each round of play, also announce the scores.
- Add logic and so that the players take turns to play first.
- Compute the percentage of wins for the man, out of all games played. Likewise announce this at the terminate of each round.
- Draw a flowchart of your logic.
Source: https://openbookproject.net/thinkcs/python/english3e/iteration.html
0 Response to "How to Print Text Over Again 100 Times in Python 35"
Post a Comment