Print Selection 1.3.3

Print Selection 1.3.3 Average ratng: 9,2/10 731 reviews
  1. Epson Easy Photo Print makes photo printing easy and quick. Main interface of Epson Easy Photo Print has three icons for selecting the photos, paper, and customizing the layout and printing. We can also see our system directory tree with all our files and folders.
  2. Print Selection یک برنامه مخصوص سیستم عامل مک می باشد که به کمک ان شما می توانید از هر جای وب ، ایمیل ، سند ها و هر چیزی که تمایل داشتید چاپ کنید! از چاپ مابقی چیز های اضافه مانند تبلیغات و لینک ها و.

Selection File type icon File name Description Size Revision Time User. Print Selection 1.3.3 Mac OS X 3.6 MB. Save ink, paper and time by printing only what you want. Print Selection integrates with OS X so you can selectively print excerpts from the web, email and documents. Stop wasting ink printing and paper banner ad or comments websites! 2-tert-Butyl-1,1,3,3-tetramethylguanidine is an organic base, also known as Barton's base. It is named after Nobel Prize-winning British chemist Derek Barton. Barton and his assistants prepared a series of guanidines with steric hinderance in 1982; in this case five. Print Selection integrates with OS X so you can selectively print snippets from the Web, email, and documents. Stop wasting ink and paper printing off banner ads or comments from websites! Accessible from the menubar or as a service, it is super easy to paste text and images into the app to print.

Source code:Lib/random.py

This module implements pseudo-random number generators for variousdistributions.

For integers, there is uniform selection from a range. For sequences, there isuniform selection of a random element, a function to generate a randompermutation of a list in-place, and a function for random sampling withoutreplacement.

On the real line, there are functions to compute uniform, normal (Gaussian),lognormal, negative exponential, gamma, and beta distributions. For generatingdistributions of angles, the von Mises distribution is available.

Almost all module functions depend on the basic function random(), whichgenerates a random float uniformly in the semi-open range [0.0, 1.0). Pythonuses the Mersenne Twister as the core generator. It produces 53-bit precisionfloats and has a period of 2**19937-1. The underlying implementation in C isboth fast and threadsafe. The Mersenne Twister is one of the most extensivelytested random number generators in existence. However, being completelydeterministic, it is not suitable for all purposes, and is completely unsuitablefor cryptographic purposes.

The functions supplied by this module are actually bound methods of a hiddeninstance of the random.Random class. You can instantiate your owninstances of Random to get generators that don’t share state.

Class Random can also be subclassed if you want to use a differentbasic generator of your own devising: in that case, override the random(),seed(), getstate(), and setstate() methods.Optionally, a new generator can supply a getrandbits() method — thisallows randrange() to produce selections over an arbitrarily large range.

The random module also provides the SystemRandom class whichuses the system function os.urandom() to generate random numbersfrom sources provided by the operating system.

Warning

The pseudo-random generators of this module should not be used forsecurity purposes. Use os.urandom() or SystemRandom ifyou require a cryptographically secure pseudo-random number generator.

Bookkeeping functions:

random.seed(a=None, version=2)

Initialize the random number generator.

If a is omitted or None, the current system time is used. Ifrandomness sources are provided by the operating system, they are usedinstead of the system time (see the os.urandom() function for detailson availability).

If a is an int, it is used directly.

With version 2 (the default), a str, bytes, or bytearrayobject gets converted to an int and all of its bits are used. With version 1,the hash() of a is used instead.

Changed in version 3.2: Moved to the version 2 scheme which uses all of the bits in a string seed.

random.getstate()

Return an object capturing the current internal state of the generator. Thisobject can be passed to setstate() to restore the state.

random.setstate(state)

state should have been obtained from a previous call to getstate(), andsetstate() restores the internal state of the generator to what it was atthe time getstate() was called.

random.getrandbits(k)

Returns a Python integer with k random bits. This method is supplied withthe MersenneTwister generator and some other generators may also provide itas an optional part of the API. When available, getrandbits() enablesrandrange() to handle arbitrarily large ranges.

Functions for integers:

random.randrange(stop)
random.randrange(start, stop[, step])

Return a randomly selected element from range(start,stop,step). This isequivalent to choice(range(start,stop,step)), but doesn’t actually build arange object.

The positional argument pattern matches that of range(). Keyword argumentsshould not be used because the function may use them in unexpected ways.

Changed in version 3.2: randrange() is more sophisticated about producing equally distributedvalues. Formerly it used a style like int(random()*n) which could produceslightly uneven distributions.

random.randint(a, b)

Return a random integer N such that a<=N<=b. Alias forrandrange(a,b+1).

Functions for sequences:

random.choice(seq)

Return a random element from the non-empty sequence seq. If seq is empty,raises IndexError.

random.shuffle(x[, random])

Shuffle the sequence x in place. The optional argument random is a0-argument function returning a random float in [0.0, 1.0); by default, this isthe function random().

Note that for even rather small len(x), the total number of permutations ofx is larger than the period of most random number generators; this impliesthat most permutations of a long sequence can never be generated.

random.sample(population, k)

Return a k length list of unique elements chosen from the population sequenceor set. Used for random sampling without replacement.

Returns a new list containing elements from the population while leaving theoriginal population unchanged. The resulting list is in selection order so thatall sub-slices will also be valid random samples. This allows raffle winners(the sample) to be partitioned into grand prize and second place winners (thesubslices).

Members of the population need not be hashable or unique. If the populationcontains repeats, then each occurrence is a possible selection in the sample.

To choose a sample from a range of integers, use an range() object as anargument. This is especially fast and space efficient for sampling from a largepopulation: sample(range(10000000),60).

If the sample size is larger than the population size, a ValueErroris raised.

Print selection 1.3.3 tool

The following functions generate specific real-valued distributions. Functionparameters are named after the corresponding variables in the distribution’sequation, as used in common mathematical practice; most of these equations canbe found in any statistics text.

random.random()

Return the next random floating point number in the range [0.0, 1.0).

random.uniform(a, b)

Return a random floating point number N such that a<=N<=b fora<=b and b<=N<=a for b<a.

The end-point value b may or may not be included in the rangedepending on floating-point rounding in the equation a+(b-a)*random().

random.triangular(low, high, mode)

Return a random floating point number N such that low<=N<=high andwith the specified mode between those bounds. The low and high boundsdefault to zero and one. The mode argument defaults to the midpointbetween the bounds, giving a symmetric distribution.

random.betavariate(alpha, beta)

Beta distribution. Conditions on the parameters are alpha>0 andbeta>0. Returned values range between 0 and 1.

random.expovariate(lambd)

Exponential distribution. lambd is 1.0 divided by the desiredmean. It should be nonzero. (The parameter would be called“lambda”, but that is a reserved word in Python.) Returned valuesrange from 0 to positive infinity if lambd is positive, and fromnegative infinity to 0 if lambd is negative.

random.gammavariate(alpha, beta)

Gamma distribution. (Not the gamma function!) Conditions on theparameters are alpha>0 and beta>0.

The probability distribution function is:

random.gauss(mu, sigma)

Gaussian distribution. mu is the mean, and sigma is the standarddeviation. This is slightly faster than the normalvariate()Avid media composer 8.4.5 + patch download pc. functiondefined below.

random.lognormvariate(mu, sigma)

Log normal distribution. If you take the natural logarithm of thisdistribution, you’ll get a normal distribution with mean mu and standarddeviation sigma. mu can have any value, and sigma must be greater thanzero.

random.normalvariate(mu, sigma)

Normal distribution. mu is the mean, and sigma is the standard deviation.

random.vonmisesvariate(mu, kappa)

mu is the mean angle, expressed in radians between 0 and 2*pi, and kappais the concentration parameter, which must be greater than or equal to zero. Ifkappa is equal to zero, this distribution reduces to a uniform random angleover the range 0 to 2*pi.

random.paretovariate(alpha)

Pareto distribution. alpha is the shape parameter.

random.weibullvariate(alpha, beta)

Weibull distribution. alpha is the scale parameter and beta is the shapeparameter.

Alternative Generator:

class random.SystemRandom([seed])

Class that uses the os.urandom() function for generating random numbersfrom sources provided by the operating system. Not available on all systems.Does not rely on software state, and sequences are not reproducible. Accordingly,the seed() method has no effect and is ignored.The getstate() and setstate() methods raiseNotImplementedError if called.

See also

M. Matsumoto and T. Nishimura, “Mersenne Twister: A 623-dimensionallyequidistributed uniform pseudorandom number generator”, ACM Transactions onModeling and Computer Simulation Vol. 8, No. 1, January pp.3-30 1998.

Complementary-Multiply-with-Carry recipe for a compatible alternativerandom number generator with a long period and comparatively simple updateoperations.

9.6.1. Notes on Reproducibility¶

Sometimes it is useful to be able to reproduce the sequences given by a pseudorandom number generator. By re-using a seed value, the same sequence should bereproducible from run to run as long as multiple threads are not running.

Most of the random module’s algorithms and seeding functions are subject tochange across Python versions, but two aspects are guaranteed not to change:

  • If a new seeding method is added, then a backward compatible seeder will beoffered.
  • The generator’s random() method will continue to produce the samesequence when the compatible seeder is given the same seed.

9.6.2. Examples and Recipes¶

Basic usage:

A common task is to make a random.choice() with weighted probabilities.

If the weights are small integer ratios, a simple technique is to build a samplepopulation with repeats:

A more general approach is to arrange the weights in a cumulative distributionwith itertools.accumulate(), and then locate the random value withbisect.bisect():

Modern computers can do millions or even billions of instructions asecond. With the techniques discussed so far, it would be hard toget a program that would run by itself for more than a fraction ofa second.

Practically, we cannot write millions of instructions to keepthe computer busy. To keep a computer doing useful work we needrepetition, looping back over the same block of code again andagain. There are two Python statement types to do that: the simplerfor loops, which we take up shortly, and while loops, whichwe take up later, in While Statements.

Two preliminaries:

  1. The value of already defined variables can beupdated. This will be particularly important in loops. To prepare for that wefirst follow how variables can be updated in an even simplersituation, where statements are just executed in textual order.
  2. Sequence types are used in for loops. We willlook at a basic sequence type: list.

Then we put this all together. This is a longsection. Go slowly and carefully.

1.13.1. Updating Variables¶

The programs so far have defined and used variables, but other thanin early shell examples we have not changed the value of existingvariables. For now consider a particularly simple example, justchosen as an illustration, in the example file updateVar.py:

Can you predict the result? Run the program and check.Particularly if you did not guess right, it is important tounderstand what happens, one step at a time. That means keepingtrack of what changes to variables are made by each statement.

In the table below, statements are referred to by the numbers labelingthe lines in the code above. We can track the state of eachvariable after each line is executed. A dash is shown where avariable is not defined. For instance after line 1 is executed, avalue is given to x, but y is still undefined. Then y gets a valuein line 2. The comment on the right summarizes what is happening.Since x has the value 3 when line 2 starts, x+2 is the same as 3+2.In line three we use the fact that the right side of an assignmentstatement uses the values of variables when the line startsexecuting (what is left after the previous line of the tableexecuted), but the assignment to the variable y on the left causesa change to y, and hence the updated value of y, 10, is shown inthe table. Line 4 then changes x, using the latest value of y(10, not the initial value 5!). The result from line 5 confirms thevalues of x and y.

LinexyComment
13-
2355=3+2, using the value of x from the previous line
331010=2*5 on the right, use the value of y from theprevious line
47107=10-3 on the right, use the value of x and y from theprevious line
5710print: 7 10

When we create such a table,the order of execution will always be the order of the lines in thetable. In this simple sequential code, that also follows thetextual order of the program. Following each line of execution of aprogram in the proper order of execution, carefully,keeping track of the current values ofvariables, will be called playing computer. A table like the oneabove is an organized way to keep track.

1.13.2. The list Type¶

Lists are ordered sequences of arbitrary data. Lists are the firstkind of data discussed so far that are mutable: the length of thesequence can be changed and elements substituted. We will delay thediscussion of changes to lists until a further introduction toobjects. Lists can be written explicitly. Read the followingexamples

The basic format is a square-bracket-enclosed, comma-separated listof arbitrary data.

1.13.3. The range Function, Part 1¶

There is a built-in function range, that can be used toautomatically generate regular arithmetic sequences. Try thefollowing in the Shell:

The general pattern for use is

range(sizeOfSequence)

This syntax will generate the integers, one at a time, as needed[1]. Ifyou want to see all the results at once as a list, you can convertto a list as in the examples above. The resulting sequence startsat 0 and ends before the parameter. We will see there are goodreasons to start from 0 in Python. One important property ofsequences generated by range(n) is that the total number ofelements is n: The sequence omits the number n itself, butincludes 0 instead.

With more parameters, the range function can be used togenerate a much wider variety of sequences. The elaborations arediscussed in Random Colors andThe Most General range Function.

[1]In computer jargon, producing values of a sequence only as needed is calledlazy evaluation.

1.13.4. Basic for Loops¶

Try the following in the Shell. You get a sequence ofcontinuation lines before the Shell responds.After seeing the colon at the end of the first line,the Shell knows later lines are to be indented.

Be sure to enter another empty line. (Just press Enter.)at the end to get the Shell to respond. :

This is a for loop. It has the heading starting with for,followed by a variable name (count in this case), the wordin, some sequence, and a final colon. As with functiondefinitions and other heading lines, the colonat the end of the line indicates that a consistently indented blockof statements follows to complete the for loop.

The block of lines is repeated once for each element of thesequence, so in this example the two lines in the indented blockare repeated three times. Furthermore the variable in the heading(count here) may be used in the block, and each time through ittakes on the next value in the sequence, so the first timethrough the loop count is 1, then 2, and finally 3. Look againat the output and see that it matches this sequence. A more detailedsequence is given, playing computer, in the table:

Linecountcomment
11start with the first element of the list
21print 1
31‘yes’ * 1 is ‘yes’; print yes
12change count to the next element in the list
22print 2
32‘yes’ * 2 is ‘yesyes’; print yesyes;
13change count to the next element in the list
23print 3
33‘yes’ * 3 is ‘yesyesyes’; print yesyesyes; done with list

When executing step by step, note that the for loop heading serves twopurposes:

  • Each time the heading line executes, it implicitly assigns a new value tothe variable name you use in place of item.
  • After each execution of the heading line, the statements in theindented block are executed,generally making use of the the new value for the variable assigned in theheading.

Note

When playing computer with a loop, the same line numbers canreappear over and over, because the for loop heading lineand the indented body under it are each executed repeatedly.Each time one of these lines is executed, it must be listed separately,in time sequence!

A for loop is technically a single compound statement.Its level of indentation is considered to bethe level of indentation of its heading.

When you used the Shell to enter a loop,there was a reason that the interpreter waited to respond until after youentered an empty line: The interpreter did not know how long theloop block was going to be! The empty line is a signal to theinterpreter that you are done with the loop block, and hence ready toexecute the complete compound loop statement.

Look at the following example program for123.py, and run it.

In a file, where the interpreter does not need to respondimmediately, the blank line is not necessary. Instead, as with afunction definition or any other format with an indented block, youindicate being past the indented block by dedenting.Here the following print statement has the same level of indentationas the for loop heading. Because they have the same level ofindentation, they are executed in sequence. Hence in the code above,“Done Counting.” is printed once after the first loop completesall of its repetitions.Execution of the program ends with another simple loop.

As with the indented block in a function, it is important to getthe indentation right. Alter the code above, so the fourth line isindented:

Predict the change, and run the code again to test.

Loops are one of the most important features in programming. Whilethe for loop syntax is pretty simple, using them creatively to solveproblems (rather than just look at a demonstration) is among thebiggest challenges for many learners at an introductory level. Oneway to simplify the learning curve is to classify common situationsand patterns, and give them names.One of the simplest patterns is illustrated in all of the for loop examplesso far, a simple for-each loop: For each element of the sequence,do the same sort of thing with it. Stated as more Pythonic pseudo-code:

(It would be even more like English if for were replace byforeach, but the shorter version is the one used by Python.)

In the for loop examples above, something is printed that isrelated to each item in the list. Printing is certainly one form of“do something”, but the possibilities for “do something” arecompletely general!

We can use a for-each loop to revise our first example in the Tutorial. Recallthe code from madlib.py:

Each line is doing exactly the same thing, except varying thestring used as the cue, while repeating the rest of the line. Thisis the for-each pattern, but we need to list the sequence that thecues come from. Read the alternative:

Seeingthis feature requires the ability to abstract the general pattern fromthe group of examples. This is essential for using loops effectively.

If you wish to see or run the whole program with this smallmodification, see the example madlibloop.py. A common naming convention is usedin the program:Each element in the list is a cue, while the list with all the elements isnamed with the plural cues. In later situations I make a list name be theplural of the variable name used for an individual item of the list.

Note the logic of the transformation between the two program versions:The alternative pieces of data are collected in the list in thefor loop heading.A singlevariable name (here I chose cue) is used in the heading as a placeholderto refer to the current choice being handled, and the body refers to thisvariable cue in place of the explicit data values included each timein the original no-loop version.

It is important to understand the sequence of operations, howexecution goes back and forth between the heading and the body.Here are the details:

  1. heading first time: variable cue is set to the first elementof the sequence, 'animal'
  2. body first time: since cue is now 'animal', effectivelyexecute addPick('animal',userPicks) (Skip the details of thefunction call in this outline.)
  3. heading second time: variable cue is set to the next elementof the sequence, 'food'
  4. body second time: since cue is now 'food', effectivelyexecute addPick('food',userPicks)
  5. heading third time: variable cue is set to the next (last)element of the sequence, 'city'
  6. body third time: since cue is now 'city', effectivelyexecute addPick('city',userPicks)
  7. heading done: Since there are no more elements in the sequence,the entire for loop is done and execution would continue withthe statement after it (not indented).

In this example the data values are just a few given literals,and there is only one line in the repeated pattern. Hence the use of a for loopis not a big deal, but it makes a simple example!This looping construction would be much handier if you were tomodify the original mad lib example, and had a story with many morecues. Also this revision will allow for further improvements inThe Revised Mad Lib Program, after we introduce more about stringmanipulation.

1.13.4.1. Pattern Loop Exercise¶

Write a two-line for-each loop in a file types2.pycontaining a call to the type function, so thatthis code with the for-each loopproduces exactly the same printed outputas the code in example file types1.py.The types1.py code is shown below:

Execute both versions to check yourself. Hint 1: [2] Hint 2: [3]

1.13.4.2. Triple Exercise¶

Complete the following function. This starting code is intripleStub.py. Save it to the new name triple.py. Notethe way an example is given in the documentation string. Itsimulates the use of the function in the Shell. This is a commonconvention:

[2]The elements of the list in the for loop headingare not all of the same type.
[3]You need to use the loop variable twice in the loop body.

1.13.5. Simple Repeat Loop¶

The examples above all used the value of the variable in thefor loop heading. An even simpler for loop usage is whenyou just want to repeat the exact same thing a specific number oftimes. In that case only the length of the sequence, not theindividual elements are important. We have already seen that therange function provides an easy way to produce a sequence witha specified number of elements. Read and run the example programrepeat1.py:

In this situation, the variable i is not used inside the bodyof the for-loop.

The user could choose the number of times to repeat. Read and runthe example program repeat2.py:

When you are reading code, you look at variable names as they are introduced,and see where they are used later.In the simple repeat loops above, the loop variable i is introduced,because there must be a variable name there, but it is never used.

One convention to indicate the simple repeat loop variable isnever used again, is to use the special variable name _ (just an underscore),as in:

1.13.6. Successive Modification Loops¶

Suppose I have a list of items called items, and I want toprint out each item and number them successively. For instance ifitems is ['red','orange','yellow','green'], I wouldlike to see the output:

Read about the following thought process for developing this:

If I allow myself to omit the numbers, it is easy: For any itemin the list, I can process it with

and I just go through the list and do it for each one. (Copy andrun if you like.)

Clearly the more elaborate version with numbers has a pattern withsome consistency, each line is at least in the form:

number item

but the number changes each time, and the numbers do not comestraight from the list of items.

A variable can change, so it makes sense to have a variablenumber, so we have the potential to make it change correctly.We could easily get it right the first time, and then repeat thesame number. Read and run the example programnumberEntries1.py:

Of course this is still not completely correct, since the idea wasto count. After the first time number is printed, it needs to bechanged to 2, to be right the next time through the loop, as in thefollowing code: Read and run the example programnumberEntries2.py:

This is closer, but still not completely correct, since we neverget to 3! We need a way to change the value of numberthat will work each time through the loop. The pattern ofcounting is simple, so simple in fact that you probably do notthink consciously about how you go from one number to the next: Youcan describe the pattern by saying each successive number isone more than the previous number. We need to be able to changenumber so it is one more than it was before. That is theadditional idea we need! Change the last line of the loop body toget the example program numberEntries3.py. See the addition and runit:

It is important to understand the step-by-step changes duringexecution. Below is another table showing the results of playingcomputer. The line numbers are much more important here to keeptrack of the flow of control, because of the jumping around at theend of the loop.

Again note that the program line numbers in the Line column of theplaying computertable are not all listed sequentially, because the for loop heading lineand the indented body under it are each executed repeatedly.

For compactness, the variable items does not get its own column,since it always has the value shown in the comment in line 1:

lineitemnumbercomment
1--set items to [‘red’, ‘orange’,’yellow’, ‘green’]
2-1
3‘red’1start with item as first in sequence
4‘red’1print: 1 red
5‘red’22 = 1+1
3‘orange’2on to the next element in sequence
4‘orange’2print 2 orange
5‘orange’33=2+1
3‘yellow’3on to the next element in sequence
4‘yellow’3print 3 yellow
5‘yellow’44=3+1
3‘green’4on to the last element in sequence
4‘green’4print 4 green
5‘green’55=4+1
3‘green’5sequence done, end loop and code

The final value of number is never used, but that is OK. What wewant gets printed.

Go through carefully andbe sure you understand the meaning of each entry in the table, and thereason for the sequencing and the reason for the exact position ofeach entry in each step where it changes!In particular see how and why the line number for eachsuccessive row is not always one more than the previous row. Inparticular, see how the same sequence of numbered lines may be repeatedin multiple places in the table.Without this understanding you will not be able to play computer yourselfand really understand loops.

This short example illustrates a lot of ideas important to loops:

  • Loops may contain several variables.
  • One way a variable can change is by being the variable in afor loop heading, that automatically goes through the values in thefor loop list.
  • Another way to have variables change in a loop is to have anexplicit statement that changes the variable inside the loop,causing successive modifications.

There is a general pattern to loops with successive modification ofa variable like number above:

  1. The variables to be modified need initial values before theloop (line 1 in the example above).
  2. The loop heading causes the repetition. In a for-loop, thenumber of repetitions is the same as the size of the list.
  3. The body of the loop generally “does something” (like printabove in line 4) that you want done repeatedly.
  4. There is code inside the body of the loop to set up for thenext time through the loop, where the variable which needs tochange gets transformed to its next value (line 5 in the exampleabove).

This information can be put in a code outline:

Loop heading controlling the repetition:
Modify variables to be ready for the action the next time

If you compare this pattern to the for-each and simple repeat loopsin Basic for Loops, you see that the examples therewere simpler. There was no explicit variable modification needed toprepare for the next time though the loop. We will refer to thelatest, more general pattern as a successive modification loop.

Functions are handy for encapsulating an idea for use and reuse ina program, and also for testing. We can write a function to numbera list, and easily test it with different data. Read and run theexample program numberEntries4.py:

Make sure you can follow the whole sequence, step by step! Thisprogram has the most complicated flow of control so far, changingboth for function calls and loops.

  1. Execution start with the very last line, since the previouslines are definitions

  2. Then main starts executing.

  3. The first call to numberList effectively sets the formalparameter

    and the function executes just like the flow followed innumberEntries3.py. This time, however, execution returns tomain.

  4. An empty line is printed in the second line of main.

  5. The second call to numberList has a different actualparameter ['apples','pears','bananas'], so this effectivelysets the formal parameter this time

    and the function executes in a similar pattern as innumberEntries3.py, but with different data and one less timethrough the loop.

  6. Execution returns to main, but there is nothing more to do.

1.13.7. Accumulation Loops¶

Suppose you want to add up all the numbers in a list, nums. Letus plan this as a function from the beginning, so read the codebelow. We can start with:

If you do not see what to do right away, a useful thing to do iswrite down a concrete case, and think how you would solve it, incomplete detail. If nums is [2,6,3,8], you wouldlikely calculate:

8 + 3 is 11
19 is the answer to be returned.

Since the list may be arbitrarily long, you need a loop. Hence youmust find a pattern so that you can keep reusing thesame statements in the loop. Obviously you are using each numberin the sequence in order. You also generate a sum in each step,which you reuse in the next step. The pattern is different,however, in the first line, 2+6 is 8: there is no previous sum, andyou use two elements from the list. The 2 is not added to aprevious sum.

Although it is not the shortest way to do the calculationby hand, 2 is a sum of 0 + 2: We can make the pattern consistentand calculate:

0 + 2 is 2
8 + 3 is 11
19 is the answer.

Then the second part of each sum is a number from the list,nums. If we call the number from the list num, the maincalculation line in the loop could be

The trick is to use the same line of code the next time through theloop. That means what wasnextSum in one pass becomes thesum in the next pass. One way to handle that is:

Do you see the pattern? Again it is

loop heading:
preparation for the next time through the loop

Sometimes the two general loop steps can be combined. This is sucha case. Since nextSum is only used once, we can just substituteits value (sum) where it is used and simplify to:

so the whole function, with the return statement is:

The example program sumNums.py has the code above withthe following line added at the end to test thefunction (not indented). RunsumNums.py.

The pattern used here is certainly successive modification (of thesum variable). It is useful to give a more specialized name forthis version of the pattern here. It follows an accumulationpattern:

initialize the accumulation to include none of the sequence (sum=0 here)
new value of accumulation = result of combining item with last value of accumulation

This pattern will work in many other situations besides addingnumbers.

English loop terminology:Of course you need to be able to go from an English description of a problemto a plan and then implement it in Python. In particular,it will be very important to realizewhen you will need your program to have a loop through a sequence.What are some common words or phrases that suggest a loop?After thinking for yourself, compare: [4]

Once you see this need for a loop, you need to plan your code.There are a bunch of questions you can routinely ask yourselfabout fleshing out the outline for the loop part of your code:

loop heading:
preparation for the next time through the loop
  1. What is the sequence? What descriptive name can I give to the loop variable?
  2. Write the for loop heading.With this decided, you no longer need to think about the whole program at once:You can focus on what you do for one element, with the name you gavein the loop heading.
  3. What do I need to do for a single element of the sequence?Does this involve other variables? If so, how will I initialize them?Write this action into the body of the loop, using the loop variable.
  4. Does the main action involve a variable, other than the loop variable,that needs to change each time through the loop?If so, how do I relate the present and next values,and change the value to beready for the next time through the loop?Writing the sequence for a specific example may help.Finally, code this update.

1.13.7.1. Play Computer sumList Exercise¶

Suppose the function sumList, defined above,is called with the parameter[5,2,4,7]. Play computer on this call, using the fileplayComputerSumStub.rtf, openedfrom an operating system windowfor the examples directory. Do not open in Idle.The file should come up in your usual word processor.Immediately save the file asplayComputerSum.rtf, and fill in blank cells in the table.

Make sure there is arow in the table for each line executed in the program,with a separate line entry for each time a line is executed.In each row enter which program line is beingexecuted, and show all changes caused to variables by the executionof that one line.Display line numbers as shown in the margin beside the example codein the Tutorial.(The separate Python files themselves do not show the line numbers.)A table is started for you below. The final row that you enter in youryour table should be for an execution of line numbered 6 in the code,and your comment can be, “return 18”.

If the same variable value in one column repeats through several rows,it is more convenient just leave the later entries blank, rather thankeep copying. With this convention, the current value of a variableis the last value recorded in a previous line in the table.

This is the first “Play Computer” exercise with a loop.Be sure to look back at the earlier play computer examples. The linesin the loop (and hence their line numbers) repeat multiple timesas rows in the table, as you followthe loop one time through after another!

The original parameter, which does not change, does not have acolumn in the table,for compactness. The start of the table is shown below.As shown in the first comment,throughout the function call, nums is

Linesumnumcomment
1--set nums to [5, 2, 4, 7]; skip line 2 doc string
3

1.13.7.2. Test sumList Exercise¶

Write a program testSumList.py which includes a mainfunction to test the sumList function several times. Include a testfor the extreme case, with an empty list.

1.13.7.3. Join All Exercise¶

* Complete the following function. This starting code is injoinAllStub.py. Save it to the new name joinAll.py. Notethe way an example is given in the documentation string. Itsimulates the use of the function in the Shell. This is a commonconvention:

First Hint: [5]Second Hint: [6]

1.13.8. More Playing Computer¶

Testing code by running it is fine, but looking at the results doesnot mean you really understand what is going on, particularly ifthere is an error! People who do not understand what is happeningare likely to make random changes to their code in an attempt tofix errors. This is a very bad, increasingly self-defeatingpractice, since you are likely to never learn where the realproblem lies, and the same problem is likely to come back to biteyou.

It is important to be able to predict accurately what code will do.We have illustrated playing computer on a variety of small chunksof code.

Playing computer can help you find bugs (errors in your code). Someerrors are syntax errors caught by the interpreter in translation.Some errors are only caught by the interpreter during execution,like failing to have a value for a variable you use. Other errorsare not caught by the interpreter at all - you just get the wronganswer. These are called logical errors. Earlier logical errorscan also trigger an execution error later. This is when playingcomputer is particularly useful.

A common error in trying to write the numberList function wouldbe to have the following code(extracted from numberEntriesWRONG.py):

You can run this code and see that itproduces the wrong answer. If you play computer on the call tonumberList(['apples','pears','bananas']), you can see theproblem:

Lineitemnumbercomment
1--set items to [‘apples’, ‘pears’, ‘bananas’]
3‘apples’-start with item as first in sequence
4‘apples’1
5‘apples’11 print: 1 apples
6‘apples’22 = 1+1
3‘pears’2on to the next element in sequence
4‘pears’1
5‘pears’1print: 1 pears OOPS!

If you go step by step you should see where the incorrect 1 camefrom: the initialization is repeated each time in the loop at line4, undoing the incrementing of number in line 6, messing upyour count.

Warning

Always be careful that your one-time initializationfor a loop goes before the loop, not in it!

Functions can also return values. Consider the Python for thismathematical sequence: define the function m(x) = 5x, let y = 3;find m(y) + m(2y-1):

This code is in example mathfunc.py.A similar example was considered in Returned Function Values,but now add the idea of playingcomputer and recording the sequence in a table. Like when yousimplify a mathematical expression, Python must complete theinnermost parts first. Tracking the changes means following thefunction calls carefully and using the values returned. Again adash ‘-‘ is used in the table to indicate an undefined variable.Not only are local variables like formal parameters undefinedbefore they are first used, they are also undefined after thetermination of the function,

LinexyComment
1-3Remember definition of m
4-3
5-3start on: print(m(y) + m(2*y-1)); first want m(y), which is m(3)
133pass 3 to function m, so x =3
233return 5*3 = 15
5-3substitute result: print(15 + m(2*y-1)), want m(2*y-1), which is m(2*3-1) = m(5)
153pass 5 to function m, so x=5
253return 5*5 = 25
5-3substitute result: print(15 + 25), so calculate and print 40

Thus far most of the code given has been motivated first, so youare likely to have an idea what to expect. You may need to readcode written by someone else (or even yourself a while back!) whereyou are not sure what is intended. Also you might make a mistakeand accidental write code that does something unintended! If youreally understand how Python works, one line at a time, you shouldbe able to play computer and follow at least short code sequencesthat have not been explained before. It is useful to read anotherperson’s code and try to follow it. The next exercises alsoprovides code that has not been explained first, or has a mistake.

1.13.8.1. Play Computer Odd Loop Exercise¶

* Work in a word processor (not Idle!),starting from example playComputerStub.rtf, and save the file asplayComputer.rtf. The file hastables set up for this and the following two exercise.

Play computer on the following code:

Reality check: 31 isprinted when line 6 finally executes.The start of the table for this exercise is shown below.

LinexynComment
10

1.13.8.2. Play Computer Error Exercise¶

* In a word processoradd to the file playComputer.rtf, started in the previous exercise.

The following code is supposed to compute the product ofthe numbers in a list. For instance product([5,4,6]) shouldcalculate and return 5*4*6=120 in steps, calculating 5,5*4=20 and 20*6=120.

The code for this exerciseappears in the example file numProductWrong.py.

A major use of playing computer is to see exactly where thedata that you expect gets messed up. Play computer on a call toproduct([5,4,6])until you see that it makes a mistake,and produces a wrong number.Then you can stop extending the table, just ending with a commentabout how the error is now visible.

The tableheadings and the first row of the table for this exercise are shown below.

LinenprodComment
1--Set nums to [5, 4, 6]
2

Then you can stop and fix it: First copy numProductWrong.py tonumProduct.py, and fix the new file (and save again!).

1.13.8.3. Play Computer Functions Exercise¶

* In a word processor once againadd to the file playComputer.rtf, started in the previous exercises.

Play computer on the following code:

Reality check: 70 is printed.

The tableheadings and the first row of the table for this exercise are shown below.

LinexComment
1-2Remember f definition
3

You will revisit line 3 several times, with table lines forfunction f execution interspersed.Look at the example above which has a table showing function mreturning a value twice!

1.13.9. The print function keyword end

By default the print function adds a newline to the end of thestring being printed. This can be overridden by including thekeyword parameter end. The keyword end can be set equal to anystring. The most common replacements are the empty string or asingle blank. If you also use the keyword parameter sep, thesekeyword parameters may be in either order, but keyword parameters must come at theend of the parameter list. Read the illustrations:

is equivalent to

This does not work directly in the shell (where you are alwaysforced to a new line at the end). It does work in a program, but itis not very useful except in a loop!

Suppose I want to print a linewith all the elements of a list, separated by spaces, but not onseparate lines. I can use the end keyword set to a space in theloop. Can you figure out in your head what this example fileendSpace1.py does? Then try it:

If you still want to go on to a new line at the end of the loop,you must include a print function that does advance to the nextline, once, after the loop. Try this variation, endSpace2.py

[4]“do each”, “do every”, “for all”, “process each”, “do ___ times”, ..
[5]This is a form of accumulation, but not quite the same as addingnumbers.
[6]“Start with nothing accumulated” does not mean 0, here.You are dealing with strings, not numbers. Thinkwhat is appropriate.