Whenever I Loop Again the Numbers Just Add
3.three.i. Uncomplicated while
Loops¶
Other than the trick with using a render
statement inside of a for
loop, all of the loops and then far take gone all the way through a specified list. In whatever case the for
loop has required the use of a specific list. This is often too restrictive. A Python while
loop behaves quite similarly to mutual English language usage. If I say
While your tea is also hot, add together a fleck of ice.
Presumably you would test your tea. If it were too hot, y'all would add together a footling ice. If y'all exam again and it is still too hot, you would add ice again. As long as you tested and establish it was truthful that your tea was likewise hot, you would go back and add more water ice. Python has a similar syntax:
while
status:
- indentedBlock
Setting up the English language example in a similar format would be:
- while your tea is too hot :
- add a chip of ice
To make things concrete and numerical, suppose the following: The tea starts at 115 degrees Fahrenheit. You desire it at 112 degrees. A chip of ice turns out to lower the temperature one degree each time. You lot test the temperature each fourth dimension, and besides print out the temperature before reducing the temperature. In Python you lot could write and run the code below, saved in example program cool.py:
temperature = 115 while temperature > 112 : # get-go while loop code impress ( temperature ) temperature = temperature - i print ( 'The tea is cool enough.' ) |
I added a concluding line later on the while loop to remind you that execution follows sequentially afterwards a loop completes.
If you play reckoner and follow the path of execution, you could generate the following table. Recollect, that each time you lot reach the stop of the indented block after the while
heading, execution returns to the while
heading for another test:
Line | temperature | Comment |
---|---|---|
1 | 115 | |
2 | 115 > 112 is true, do loop | |
3 | prints 115 | |
iv | 114 | 115 - one is 114, loop back |
2 | 114 > 112 is truthful, do loop | |
iii | prints 114 | |
4 | 113 | 114 - 1 is 113, loop back |
2 | 113 > 112 is truthful, practice loop | |
iii | prints 113 | |
four | 112 | 113 - ane is 112, loop dorsum |
2 | 112 > 112 is false, skip loop | |
6 | prints that the tea is cool |
Each time the end of the indented loop body is reached, execution returns to the while
loop heading for another test. When the exam is finally false, execution jumps past the indented body of the while
loop to the adjacent sequential statement.
A while
loop generally follows the pattern of the successive modification loop introduced with for
-each loops:
initialization
while
continuationCondition:
do main action to be repeated
prepare variables for the next time through the loop
Exam yourself: Following the code. Figure out what is printed. :
i = 4 while i < 9 : print ( i ) i = i + two
Check yourself by running the example program testWhile.py
.
Note
In Python, while
is not used quite like in English. In English you could mean to stop as soon every bit the condition you want to test becomes fake. In Python the test is but made when execution for the loop starts (or starts once again), not in the middle of the loop.
Predict what will happen with this slight variation on the previous instance, switching the lodge in the loop body. Follow it carefully, one pace at a fourth dimension.
i = four # variation on testWhile.py while ( i < ix ): i = i + 2 print ( i ) |
Bank check yourself by running the case program testWhile2.py
.
The sequence social club is important. The variable i
is increased before it is printed, so the first number printed is 6. Another mutual fault is to assume that 10 volition non be printed, since 10 is past 9, but the test that may stop the loop is not made in the middle of the loop. Once the body of the loop is started, it continues to the end, even when i
becomes 10.
Line | i | Comment |
---|---|---|
1 | four | |
two | 4 < nine is true, do loop | |
3 | 6 | iv+ii=half dozen |
4 | impress six | |
ii | six < 9 is truthful, do loop | |
3 | 8 | 6+2= 8 |
four | print 8 | |
2 | 8 < 9 is truthful, exercise loop | |
3 | 10 | 8+ii=x No test here |
4 | impress 10 | |
ii | 10 < ix is fake, skip loop |
Predict what happens in this related little programme:
nums = list () i = 4 while ( i < 9 ): nums . append ( i ) i = i + 2 print ( nums )
Check yourself by running the example programme testWhile3.py
.
3.3.2. The Most General range
Function¶
There is actually a much simpler fashion to generate the previous sequences like in testWhile3.py
, using a further variation of the range
role. Enter these lines separately in the Shell. As in the simpler applications of range
, the values are only generated ane at a time, as needed. To see the entire sequence at once, convert the sequence to a list before printing:
nums = range ( four , 9 , 2 ) print ( list ( nums ))
The third parameter for the range function is the step size. Information technology is needed when the stride size from one element to the adjacent is not 1.
The nearly general syntax is
range(
first,
pastEnd,
footstep)
The value of the 2nd parameter is always by the last element of the listing. Each element after the first in the listing is footstep more than the previous i. Predict and try in the Shell:
Actually the range part is even more than sophisticated than indicated by the while
loop above. The pace size can exist negative. Try in the Shell:
Do you see how 0 is past the cease of the listing?
Endeavor it: Make up a range
role call to generate the list of temperatures printed in the tea example, 115, 114, 113
. Exam information technology in the Trounce.
These ranges, like the simpler ranges that we used earlier, are nigh often used as the sequence in a for
loop heading:
for i in range ( x , 0 , - 1 ): # countdown... print ( i ) print ( 'Alpha!' )
three.three.3. Interactive while
Loops¶
The earlier examples of while loops were chosen for their simplicity. Obviously they could have been rewritten with range office calls. Now lets try a more interesting example. Suppose yous want to allow a user enter a sequence of lines of text, and want to remember each line in a list. This could easily be done with a simple repeat loop if you knew the number of lines to enter. For example, in readLines0.py
, the user is prompted for the exact number of lines to exist entered:
lines = list () n = int ( input ( 'How many lines exercise you want to enter? ' )) for i in range ( n ): line = input ( 'Next line: ' ) lines . append ( line ) impress ( 'Your lines were:' ) # check at present for line in lines : impress ( line )
The user may desire to enter a bunch of lines and not count them all alee of fourth dimension. This means the number of repetitions would non be known ahead of time. A while
loop is appropriate here. There is still the question of how to test whether the user wants to keep. An obvious but verbose way to do this is to ask before every line if the user wants to continue, as shown below and in the example file readLines1.py
. Read it and and so run information technology:
lines = list () testAnswer = input ( 'Press y if you want to enter more than lines: ' ) while testAnswer == 'y' : line = input ( 'Adjacent line: ' ) lines . append ( line ) testAnswer = input ( 'Printing y if you want to enter more lines: ' ) print ( 'Your lines were:' ) for line in lines : impress ( line )
See the 2 statements setting testAnswer
: 1 before the while
loop and ane at the lesser of the loop body.
Note
The data must exist initialized before the loop, in order for the showtime test of the while condition to work. Besides the test must work when you loop back from the end of the loop body. This ways the data for the exam must also be gear up a 2d time, in the loop body (ordinarily as the action in the last line of the loop). It is easy to forget the second fourth dimension!
The readLines1.py
code works, just it may exist more annoying than counting alee! Two lines must exist entered for every one you actually want! A applied alternative is to use a sentinel: a piece of data that would not make sense in the regular sequence, and which is used to point the end of the input. You lot could agree to use the line Done!
Fifty-fifty simpler: if you assume all the real lines of data will actually have some text on them, use an empty line every bit a sentinel. (If you think nigh it, the Python Shell uses this arroyo when you enter a statement with an indented body.) This manner you only need to enter one actress (very simple) line, no matter how many lines of real data y'all have.
What should the while condition be now? Since the sentinel is an empty line, you might think line == ''
, but that is the termination condition, non the continuation condition: You need the opposite condition. To negate a condition in Python, you may use not
, like in English language,
Of course in this situation at that place is a shorter style,
Run the example plan readLines2.py
, shown below:
lines = listing () impress ( 'Enter lines of text.' ) print ( 'Enter an empty line to quit.' ) line = input ( 'Side by side line: ' ) # initalize before the loop while line != '' : # while NOT the termination condition lines . suspend ( line ) line = input ( 'Side by side line: ' ) # !! reset value at end of loop! print ( 'Your lines were:' ) for line in lines : print ( line )
Once more the data for the examination in the while loop heading must be initialized earlier the first time the while
statement is executed and the test data must also be made set up inside the loop for the test after the body has executed. Hence you encounter the statements setting the variable line
both before the loop and at the terminate of the loop body. It is easy to forget the second identify within the loop!
Later on reading the rest of this paragraph, annotate the terminal line of the loop out, and run it over again: It will never stop! The variable line
will forever take the initial value you gave it! You lot really can stop the program by entering Ctrl-C
. That means hold the Ctrl
key and press c
.
Note
As y'all cease coding a while
loop, it is good practice to e'er double-check: Did I make a change to the variables, inside the loop, that will eventually make the loop condition Imitation
?
The earliest while
loop examples had numerical tests and the code to get ready for the next loop just incremented a numerical variable past a stock-still corporeality. Those were simple examples but while
loops are much more than general! In the interactive loop nosotros have seen a continuation condition with a string test, and getting fix for the next time through the loop involves input from the user.
Some of the exercises that follow involve interactive while loops. Others were delayed until here merely because they accept a wider variety of continuation condition tests and ways to prepare for the side by side fourth dimension through the loop. What is consequent is the full general steps to think of and questions to inquire yourself. They go on on applying! Go along these in mind!
- the need to run across whether there is a kind of repetition, fifty-fifty without a fixed collection of values to work through
- to think from the specific state of affairs and effigy out the continuation status that makes sense for your loop
- to think what specific processing or results you want each fourth dimension through the loop, using the same code
- to figure out what supporting code you need to brand you set for the next time through the loop: how to brand the aforementioned results code have new data values to procedure each time through, and eventually accomplish a stopping point.
Detecting the need for while
statements: Similar with planning programs needing``for`` or if
statements, you want to be able to interpret English descriptions of problems that would naturally include while
statements. What are some words or phrases or ideas that suggest the use of these statements? Recall of your own and then compare to a few I gave: [ane]
three.3.3.1. Interactive Sum Do¶
Write a program sumAll.py
that prompts the user to enter numbers, one per line, ending with a line containing only 0, and keep a running sum of the numbers. Merely impress out the sum later all the numbers are entered (at least in your terminal version). Practise not create a list! Each fourth dimension you read in a number, you tin immediately use it for your sum, and then exist washed with the number only entered.
three.3.iii.2. Safe Number Input Practice¶
* At that place is an result with reading in numbers with the input statement. If you make a typo and enter something that cannot be converted from a cord to the correct kind of number, a naive program will bomb. This is avoidable if you examination the string and repeat if the string is illegal. In this exercise write safe utility function replacements for the input function that work to read in a whole number, an integer or a decimal number.
All parts refer to the previous Is Number String Exercise. Part a. refers to the introduction in the previous exercise. Parts b. and c. refer to functions in the solution, isNumberStr.py
, of the previous practice. Make certain yous expect dorsum at these kickoff.
Save the instance safeNumberInputStub.py
as safeNumberInput.py
, and complete it. Information technology contains headings and documentation strings for the functions in each part of this practice.
- This part considers the simplest case, where you are trying to enter a whole number. Complete the definition of the function
safeWholeNumber
. - Consummate the function
safeInt
. This easily parallels part a. if you re-create in and employ the function (not method)isIntegerStr
. - Complete the office
safeDecimal
. This easily parallels function b. if you copy in and utilize the partisDecimalStr
.
3.3.3.3. Savings Exercise¶
The idea here is to see how many years it will have a bank account to grow to at to the lowest degree a given value, assuming a fixed annual interest. Write a program savings.py
. Prompt the user for three numbers: an initial balance, the almanac percentage for interest as a decimal, like .04 for iv%, and the final balance desired.
All the monetary amounts that yous print should exist rounded to exactly two decimal places. Outset by printing the initial balance this style. For example, if the initial residual was entered as 123.5, information technology should exist reprinted by your program as 123.50. Also impress the balance each year until the desired amount is reached or passed. The first balance at or past the target should exist the last one printed.
The math: The amount next twelvemonth is the amount now times (1 + involvement fraction), then if I take $500 now and the interest charge per unit is .04, I have $500*(1.04) = $520 after one year and later ii years I have, $520*(1.04) = $540.80....
For case, if I answer to the prompts, and enter into the programme a $500 starting residuum, .04 involvement charge per unit and a target of $550, the programme prints:
500.00 520.00 540.80 562.43
3.3.3.four. Foreign Sequence Exercise¶
* Recall Strange Function Exercise and its jumpFunc.py
which contains the function jump
: For any integer north, jump(northward) is n//2 if due north is fifty-fifty, and 3*n+1 if northward is odd.
You lot can start with one number, say due north = 3, and keep applying the jump office to the last number given, and see how the numbers jump around!
jump ( three ) = 3 * 3 + 1 = 10 ; spring ( x ) = x // two = 5 ; jump ( five ) = iii * 5 + 1 = xvi ; jump ( 16 ) = 16 // ii = eight ; leap ( 8 ) = 8 // two = 4 ; spring ( 4 ) = 4 // two = ii ; jump ( 2 ) = 2 // 2 = 1
This process of repeatedly applying the same function to the most recent result is called function iteration. In this instance you see that iterating the jump function, starting from n=3, eventually reaches the value one.
It is an open research question whether iterating the bound function from an integer n volition eventually reach 1, for every starting integer n greater than one. Researchers take simply found examples of north where it is true. Still, no general argument has been made to apply to the infinite number of possible starting integers.
In this exercise you iterate the bound function for specific starting values due north, until the result is 1.
-
Relieve example
jumpSeqStub.py
asjumpSeq.py
and consummate the missing role bodies. If you coded the functionjump
before injumpFunc.py
, you lot can copy it. You can complete eitherprintJumps
orlistJumps
offset, and exam before completing the other. Hint [2] -
Later on you have finished and saved
jumpSeq.py
re-create information technology and save the file asjumpSeqLengths.py
.First modify the master method and then it prompts the user for a value of due north, and then prints only the length of the iterative sequence from listJumps(n). Hint [3]
Then elaborate the program so it prompts the user for two integers: a lowest starting value of n and a highest starting value of n. For all integers n in the range from the lowest start through the highest start, including the highest, print a sentence giving the starting value of n and the length of the list from
listJumps(n)
. An example run:Enter lowest start: iii
Enter highest start: vi
Starting from three, spring sequence length viii.
Starting from 4, jump sequence length 3.
Starting from 5, jump sequence length 6.
Starting from 6, jump sequence length 9.
3.3.4. Graphical Applications¶
Another place where a while
loop could be useful is in interactive graphics. Suppose y'all want the user to be able to create a Polygon by clicking on vertices they choose interactively, but yous do not want them to have to count the number of vertices ahead of fourth dimension. A while
loop is suggested for such a repetitive process. As with entering lines of text interactively, there is the question of how to signal that yous are done (or how to indicate to proceed). If you make but a sure region be allowed for the Polygon, then the lookout tin be a mouse click exterior the region. The before interactive color option instance already has a method to check if a mouse click is inside a Rectangle, then that method can be copied and reused.
Creating a polygon is a unified action with a clear event, so allow's define a function. It involves a boundary rectangle and mouse clicks in a GraphWin, and may also return the Polygon constructed. Read the following start:
def polyHere ( rect , win ): ''' Draw a polygon interactively in Rectangle rect, in GraphWin win. Collect mouse clicks inside rect into the vertices of a Polygon, and always draw the Polygon created and so far. When a click goes exterior rect, terminate and return the terminal polygon. The Polygon ends up fatigued. The method draws and undraws rect. '''
It is useful to start by thinking of the objects needed, and give them names.
- A Polygon is needed. Call it
poly
. - A list of vertices is needed. Call it
vertices
. I demand to suspend to this list. It must exist initialized first. - The latest mouse click signal is needed. Telephone call information technology
pt
.
Certainly the overall process will be repetitious, choosing indicate after point. Still it may not be at all articulate how to brand an constructive Python loop. In challenging situations like this it is ofttimes useful to imagine a physical state of affairs with a limited number of steps, and then each step tin can exist written in sequence without worrying about a loop.
For instance to become upwards to a triangle (3 vertices in our list and a fourth mouse click for the lookout), y'all might imagine the following sequence, undrawing each onetime polygon before the next is displayed with the latest mouse click included:
rect . setOutline ( 'red' ) rect . describe ( win ) vertices = listing () pt = win . getMouse () vertices . append ( pt ) poly = Polygon ( vertices ) poly . draw ( win ) # with one betoken pt = win . getMouse () poly . undraw () # missing latest point vertices . suspend ( pt ) poly = Polygon ( vertices ) poly . describe ( win ) # with two points pt = win . getMouse () poly . undraw () # missing latest point vertices . suspend ( pt ) poly = Polygon ( vertices ) poly . draw ( win ) # with three points pt = win . getMouse () # assume exterior the region rect . undraw () return poly
There is a fine indicate here that I missed the starting time fourth dimension. The vertices of an existing Polygon do not get mutated in this organization. A new Polygon gets created each time with the new vertex list. The old Polygon does not go abroad automatically, and extraneous lines announced in the picture if the quondam polygon is not explicitly undrawn each fourth dimension before a new version is redrawn with an extra vertex. The final Polygon y'all draw should exist visible at the end, so in the instance above where I was assuming the 3rd click was the last for the triangle, I did not undraw
the Polygon.
The timing for each undraw
needs to exist later the next mouse click and presumably earlier the revised Polygon is created, so it could be before or subsequently the line vertices.append(pt)
. I arbitrarily chose for it to get earlier the vertices list is inverse. The balance of the gild of the lines is pretty well fixed by the bones logic.
If you think of the repetitions through a large number of loops, the process is essentially circular (every bit suggested by the word 'loop'). The trunk of a loop in Python, yet, is written as a linear sequence: one with a kickoff line and a last line, a beginning and an end. We can cutting a circular loop anywhere to become a piece with a beginning and an end. In practice, the place y'all cut the loop for Python has 1 master constraint: The processing in Python from the end of one fourth dimension through the loop to the beginning of the side by side loop is separated past the exam of the status in the heading. The continuation status in the while
heading must make sense where you cut the loop.
It can assist to look at a concrete example sequence, like the steps listed in a higher place for creating a triangle, only now assuming we do not know how many vertices volition exist chosen. The continuation condition is for pt
to be in the rectangle, so using the previously written office isInside
, the loop heading will be
while isInside ( pt , rect ):
With this condition in mind, look for where to split to loop. Information technology needs to be after a new pt
is clicked (then it can exist tested) and before the next Polygon is created (so it does non include the watch point by mistake). In particular, with the sequence above, look and see that the divide could go before or after the poly.undraw()
line. Practise Moving Undraw considers the instance where the split goes before this line. I volition keep with the selection of splitting into a Python loop after the undraw
line. This makes the loop be
while isInside ( pt , rect ): vertices . suspend ( pt ) poly = Polygon ( vertices ) poly . draw ( win ) pt = win . getMouse () poly . undraw ()
If yous follow the full sequence of required steps above for making the concrete triangle, you see that this full sequence for the loop is but repeated twice. The last time there is no poly.undraw()
step. I could redo the loop moving the undraw line to the tiptop, which acquired unlike bug (Exercise Moving Undraw beneath). Instead think how to arrive piece of work at the finish of the final time through the loop....
There are several possible approaches. You desire the undraw
line every time except for the last time. Hence it is a statement you desire sometimes and non others. That suggests an if
statement. The times you want the undraw
are when the loop will repeat again. This is the same as the continuation condition for the loop, and y'all have just read the adjacent value for pt
! You could just add a condition in front of the terminal line of the loop:
if isInside ( pt , rect ): poly . undraw ()
I detect this option unaesthetic: information technology means duplicating the continuation test twice in every loop.
Instead of avoiding the undraw
as you exit the loop, another pick in this instance is to undo information technology: just redraw the polygon 1 final time beyond the loop. This only needs to exist done once, not repeatedly in the loop. So the repetitious lines collapse neatly into the loop.
If you expect at the overall concrete sequence for the triangle, not all the lines are in the loop. You must carefully include the lines both that come earlier the loop and those that come after the loop. Make sure these lines are not put in the loop, but before or after, as indicated past the physical sequence in the example. In the stop the entire role is:
def polyHere ( rect , win ): ''' Depict a polygon interactively in Rectangle rect, in GraphWin win. Collect mouse clicks within rect into the vertices of a Polygon, and always depict the Polygon created then far. When a click goes exterior rect, stop and render the terminal polygon. The Polygon ends up drawn. The method draws and undraws rect. ''' rect . setOutline ( "red" ) rect . describe ( win ) vertices = list () pt = win . getMouse () while isInside ( pt , rect ): vertices . append ( pt ) poly = Polygon ( vertices ) poly . draw ( win ) pt = win . getMouse () poly . undraw () poly . describe ( win ) rect . undraw () return poly
Make sure you understand: Follow this code through, imagining three mouse clicks inside rect so one click exterior of rect. Compare the steps to the ones in the concrete sequence written out above and run into that the friction match (aside from the last canceling undraw
and draw
of poly
).
This function is illustrated in the example plan makePoly.py
. Other than standard graphics example lawmaking, the primary programme contains:
rect1 = Rectangle ( Point ( 5 , 55 ), Point ( 200 , 120 )) poly1 = polyHere ( rect1 , win ) poly1 . setFill ( 'green' ) rect2 = Rectangle ( Point ( 210 , fifty ), Point ( 350 , 350 )) poly2 = polyHere ( rect2 , win ) poly2 . setOutline ( 'orange' )
As you can run into, the returned polygons are used to make color changes, just every bit an illustration.
In earlier animation examples a while
loop would also have been useful. Rather than continuing the animation a fixed number of times, it would be nice for the user to indicate by a mouse click when she has watched long enough. Thus far the only way to use the mouse has been with getMouse()
. This is not going to piece of work in an animation, because the computer stops and waits for a click with getMouse()
, whereas the animation should keep until the click.
In full-fledged graphical systems that reply to events, this is no problem. Zelle's graphics is congenital on top of a capable event-driven system, and in fact, all mouse clicks are registered, fifty-fifty outside calls to getMouse()
.
As an case, run example program randomCirclesWhile.py
. Be certain to follow the prompt saying to click to starting time and to end.
Bated from the prompts, the difference from the previous randomCircles.py
program is the replacement of the original simple repeat loop heading
by the following initialization and while loop heading:
while win . checkMouse () == None : #NEW*
The graphics module remembers the last mouse click, whether or not it occurred during a phone call to getMouse()
. A style to bank check if the mouse has been clicked since the final call to getMouse()
is checkMouse()
. Information technology does non wait for the mouse as in getMouse()
. Instead it returns the remembered mouse click - the well-nigh recent mouse click in the past, unless at that place has been no mouse click since the final telephone call to getMouse or checkMouse. In that case checkMouse()
returns None (the special object used to indicate the lack of a regular object).
The checkMouse
method allows for a loop that does not stop while waiting for a mouse click, but goes on until the heading test detects that the mouse was clicked.
A like elaboration can be fabricated for the other examples of blitheness, like bounce1.py
. In bounceWhile.py
I modified bounce1.py
to take a while loop in place of the for-loop repeating 600 times. Run it. The merely slight added modification here was that win
was non originally a parameter to bounceInBox
, and then I included information technology. Look at the source code for bounceWhile.py
, with the few changes marked NEW.
In bounce2.py
I also fabricated a more interesting alter to the initialization, and so the initial management and speed of the mouse are determined graphically past the user, with a mouse click. Try example program bounce2.py
.
The program includes a new utility function to help determine the initial (dx, dy) for the animation. This is done by computing the move necessary to go from one signal (where the ball is in this program) to another (specified by a user's mouse click in this program). :
def getShift ( point1 , point2 ): # NEW utility function '''Returns a tuple (dx, dy) which is the shift from point1 to point2.''' dx = point2 . getX () - point1 . getX () dy = point2 . getY () - point1 . getY () render ( dx , dy )
Since the function calculates both a change in ten and y, information technology returns a tuple
.
A straightforward interactive method, getUserShift
, is wrapped effectually this office to get the user'south choice, which ultimately returns the same tuple:
def getUserShift ( point , prompt , win ): #NEW management selection '''Render the alter in position from the betoken to a mouse click in win. Showtime display the prompt string under betoken.''' text = Text ( Point ( point . getX (), 60 ), prompt ) text . describe ( win ) userPt = win . getMouse () text . undraw () return getShift ( point , userPt )
In the new version of the main driver, bounceBall
, excerpted below, this interactive setting of (dx, dy) is used. Notation the multiple assignment statement to both dx and dy, set from the tuple returned from getUserShift
. This shift would by and large be much too much for a unmarried blitheness step, so the actual values passed to bounceBall are scaled way down by a factor scale
.
middle = Point ( win . getWidth () / 2 , win . getHeight () / 2 ) #NEW key starting indicate ball = makeDisk ( centre , radius , win ) #NEW interactive direction and speed setting prompt = ''' Click to indicate the direction and speed of the brawl: The farther you lot click from the ball, the faster information technology starts.''' ( dx , dy ) = getUserShift ( centre , prompt , win ) calibration = 0.01 # to reduce the size of animation steps bounceInBox ( brawl , dx * scale , dy * scale , xLow , xHigh , yLow , yHigh , win )
The bounceInBox
method has the aforementioned modify to the loop as in the randomCircles.py case. The method so requires the GraphWin
, win
, as a farther parameter, since checkMouse
is a GraphWin
method.
You can look in Idle at the full source code for bounce2.py
if yous like. The changes from bounce1.py
are all marked with a comment starting with #NEW
, and all the major changes accept been described above.
In the examples and so far of the use of checkMouse()
, we have just used the fact that a betoken was clicked, not which signal. The side by side example version, bounce3.py
, does use the location of mouse clicks that are read with checkMouse()
to alter the management and speed of the brawl. Try it.
This version simply slightly modifies the central animation office, bounceInBox
, but wraps it in another looping role that makes the direction and speed of the ball alter on each mouse click. Hence the mouse clicks detected in bounceInBox
demand to be remembered and then returned later the principal animation loop finishes. That requires a name, pt
, to exist given to the last mouse click, and then it tin can be remembered. This means modifying the main animation loop to initialize the variable pt
earlier the loop and reset it at the terminate of the loop, much as in the employ of getMouse() for the interactive polygon cosmos. That explains the get-go three NEW lines and the final two NEW lines in the revised bounceInBox
:
def bounceInBox ( shape , dx , dy , xLow , xHigh , yLow , yHigh , win ): ''' Breathing a shape moving in jumps (dx, dy), bouncing when its center reaches the depression and high x and y coordinates. The animation stops when the mouse is clicked, and the last mouse click is returned.''' filibuster = . 001 pt = None #NEW while pt == None : #NEW shape . move ( dx , dy ) center = shape . getCenter () 10 = middle . getX () y = center . getY () isInside = True #NEW if 10 < xLow or 10 > xHigh : dx = - dx isInside = Imitation #NEW if y < yLow or y > yHigh : dy = - dy isInside = False #NEW time . slumber ( filibuster ) if isInside : # NEW don't mess with dx, dy when outside pt = win . checkMouse () #NEW return pt #NEW def moveInBox ( shape , stopHeight , xLow , xHigh , yLow , yHigh , win ): #NEW '''Shape bounces in win then its centre stays within the low and high 10 and y coordinates, and changes direction based on mouse clicks, terminating when at that place is a click above stopHeight.''' scale = 0.01 pt = shape . getCenter () # starts motionless while pt . getY () < stopHeight : ( dx , dy ) = getShift ( shape . getCenter (), pt ) pt = bounceInBox ( shape , dx * scale , dy * calibration , xLow , xHigh , yLow , yHigh , win ) def makeDisk ( centre , radius , win ): '''Return a cerise deejay that is drawn in win with given eye and radius.''' disk = Circumvolve ( center , radius ) disk . setOutline ( "red" ) disk . setFill ( "ruddy" ) disk . depict ( win ) return disk def getShift ( point1 , point2 ): '''Returns a tuple (dx, dy) which is the shift from point1 to point2.''' dx = point2 . getX () - point1 . getX () dy = point2 . getY () - point1 . getY () return ( dx , dy ) def bounceBall (): '''Make a ball bounciness around the screen, and react to mouse clicks.''' win = GraphWin ( 'Ball Bounce three' , 290 , 290 ) win . yUp () #NEW to mark and label the area where a click stops the program lineHeight = win . getHeight () - 40 textHeight = win . getHeight () - twenty Line ( Point ( 0 , lineHeight ), Betoken ( win . getWidth (), lineHeight )) . draw ( win ) prompt = 'Click higher up the line to stop \n or below to move toward the click.' Text ( Point ( win . getWidth () / 2 , textHeight ), prompt ) . draw ( win ) radius = 10 xLow = radius # eye is separated from the wall by the radius at a bounciness xHigh = win . getWidth () - radius yLow = radius yHigh = lineHeight - radius #NEW lower summit to bouncing limits middle = Bespeak ( win . getWidth () / 2 , lineHeight / 2 ) ball = makeDisk ( center , radius , win ) moveInBox ( ball , lineHeight , xLow , xHigh , yLow , yHigh , win ) #NEW win . close () bounceBall ()
I initially made only the changes discussed so far (not the ones involving the new variable isInside
). The variable isInside
was in response to a bug that I will discuss subsequently introducing the simple role that wraps around bounceInBox
:
Each time the mouse is clicked, the ball is to switch direction and move toward the final click, until the stopping status occurs, when there is a click above the stop line. This is clearly repetitive and needs a while loop. The condition is simply to examination the y coordinate of the mouse click against the the height of the stop line. The body of the loop is very short, since we already have the utility role getShift
, to effigy out (dx, dy) values.
def moveInBox ( shape , stopHeight , xLow , xHigh , yLow , yHigh , win ): #NEW '''Shape bounces in win so its eye stays inside the low and loftier x and y coordinates, and changes direction based on mouse clicks, terminating when at that place is a click above stopHeight.''' scale = 0.01 pt = shape . getCenter () # starts motionless while pt . getY () < stopHeight : ( dx , dy ) = getShift ( shape . getCenter (), pt ) pt = bounceInBox ( shape , dx * scale , dy * scale , xLow , xHigh , yLow , yHigh , win )
The variable pt
for the terminal mouse click needed to be initialized some way. I chose to make the value be the aforementioned as the initial position of the ball, so both dx and dy are initially 0, and the ball does not showtime in movement. (Alternatives are in Random Kickoff Exercise below.)
I occasionally detected a bug when using the program. The ball would get stuck just outside the boundary and stay at that place. The fact that information technology was slightly beyond the boundary was a clue: For simplicity I had cheated, and allowed the brawl to get just one animation step beyond the intended boundary. With the speed and modest stride size this works visually. The original code was certain to make an opposite jump back within at the adjacent step.
Subsequently some thought, I noticed that the initial version of the bounce3.py code for bounceInBox
broke that assumption. When the brawl was where a bounce-back is required, a mouse click could change (dx, dy) and mess up the bounce. The idea for a set is non to let the user modify the direction in the moment when the ball needs to bounce back.
Neither of the original boundary-checking if
statements, by itself, ever determines if the brawl is in the region where information technology needs to reverse management. I dealt with this situation by introducing a Boolean variable isInside
. Information technology is initially set up as Truthful
, and then either of the if
statements can right information technology to False. Then, at the cease of the loop, isInside
is used to make sure the brawl is safely inside the proper region when there is a check for a new mouse click and a possible user aligning to (dx, dy).
3.3.4.1. Exercise Moving Undraw¶
** As discussed in a higher place at Where to split the loop, the basic loop logic works whether the poly.undraw()
phone call is at the beginning or end of the loop. Write a variation makePoly2.py
that makes the code work the other way, with the poly.undraw()
at the beginning of the loop. Do not modify or movement any other statement in the loop. The new place to cut the loop does affect the code before and after the loop. In particular, the extra statement cartoon poly
is not needed later on the loop is completed. Make other changes to the surrounding code to make this work. Hints: [4]
iii.three.four.ii. Make Path Practise¶
** Write a program that is outwardly very like to makePoly.py
, and telephone call information technology makePath.py
, with a function pathHere
. The only outward difference between polyHere
and pathHere
is that while the first creates a closed polygon, and returns it, and the new i creates a polygonal path, without the final point beingness automatically connected to the first point, and a list of the lines in the path is returned. Internally the functions are quite different. The change simplifies some things: no need to undraw anything in the main loop - just draw the latest segment each time going from the previous point to the simply clicked point. There are complications even so: You do need deal specially with the beginning point. It has no previous bespeak to connect to. I suggest you handle this before the principal loop: If the point is inside the rectangle, draw the point and then it is a visible guide for the next point. Before returning, undraw this initial point. (The identify on the screen will still be visible if an initial segment is fatigued. If no more points were added, the screen is left bare, which is the way it should be, and an empty list of lines should exist returned.) Y'all also need to remember the previous indicate each time through the main loop. I advise yous think individually most what should happen if yous stop the drawing when the showtime, second or third betoken is exterior the rectangle. Also test each of those cases later the program is written.
In your main plan, call the makePath
office two times. Employ the listing of lines returned to loop through and change the colour of all the lines in one path and the width of the lines in the other path. A portion of a sample image from this program is shown below.
3.3.4.3. Random Offset Practice¶
* (Optional) I chose to have the ball start motionless, by making the initial value of pt
(which determines the initial (dx, dy) ) exist the center of the brawl. Write a variation startRandom.py
and then pt
is randomly chosen. Also brand the initial location of the brawl be random. You tin can copy the function getRandomPoint
from bounce1.py.
3.3.four.4. Mad Lib While Exercise¶
** Write a program madlib4.py
that modifies the getKeys
method of madlib2.py
to use a while
loop. (This is not an animation program, just this department is where you lot accept had the most experience with while loops!)
Hints: This is actually the most natural approach. I avoided while
loops initially, when but for
loops had been discussed. In the original approach, however, it is redundant to find every case of '{'
to count the number of repetitions and then find them all again when extracting the cue keys. A more natural mode to command the loop is a while
loop stopping when at that place are no further occurrences of '{'
to discover
. This involves some further adjustments. You lot must cut the loop in a dissimilar identify (to end afterward searching for '{'
). As discussed before, cut a loop in a different place may require changes earlier and subsequently the loop, too.
three.3.4.five. Find Pigsty Game Practise¶
** Write a graphical game program, findHole.py
, "Discover the Hole". The program should use a random number generator to determine a round "hole", selecting a indicate and a perhaps the radius around that point. These make up one's mind the target and are non revealed to the actor initially. The user is then prompted to click effectually on the screen to "find the hidden hole". You should show the points the user has tried. In one case the user selects a point that is within the chosen radius of the mystery point, the mystery circle should appear. At that place should be a message announcing how many steps information technology took, and the game should stop.
Hint: you have already seen the lawmaking to determine the displacement (dx, dy) between two points: employ the getShift
function in bounce2.py
. Once you have the displacement (dx, dy) betwixt the subconscious center and the latest mouse click, the altitude between the points is (dx*dx + dy*dy)**0.5
, using the Pythagorean Theorem of geometry. If this distance is no more than the radius that you have chosen for the mystery circle, then the user has found the circle! You can use getShift
as written, or alter it into a function getDistance
that directly returns the distance betwixt two points.
Many elaborations on this game are possible! Take fun with it!
3.iii.v. Fancier Blitheness Loop Logic (Optional)¶
The final variation is the case program bounce4.py
, which has the same outward beliefs as bounce3.py, just information technology illustrates a different internal design decision. The bounce3.py version has two levels of while loop in 2 methods, moveInBox
for mouse clicks and bounceInBox
for bouncing. The bounce4.py version puts all the code for changing management inside the main animation loop in the quondam outer function, moveInBox
. There are now three reasons to adapt (dx, dy): bouncing off the sides, bouncing off the top or bottom, or a mouse click. That is a simplification and unification of the logic in one sense. The complexity at present is that the logic for determining when to quit is cached deep inside the if
- else
logic, not at the heading of the loop. The test for mouse clicks is within the while
loop and further inside some other if
statement. The test of the mouse click may just lead to a change in (dx, dy), or is a bespeak to quit. Here is the revised code, with a discussion afterward of the return statement:
def moveInBox ( shape , stopHeight , xLow , xHigh , yLow , yHigh , win ): ''' Animate a shape moving toward any mouse click below stopHeight and bouncing when its eye reaches the low or high x or y coordinates. The animation stops when the mouse is clicked at stopHeight or above.''' scale = 0.01 filibuster = . 001 dx = 0 #NEW dx and dy are no longer parameters dy = 0 #NEW while True : #NEW leave loop at return statement heart = shape . getCenter () x = eye . getX () y = center . getY () isInside = Truthful if ten < xLow or x > xHigh : dx = - dx isInside = False if y < yLow or y > yHigh : dy = - dy isInside = False if isInside : pt = win . checkMouse () if pt != None : #NEW dealing with mouse click now here if pt . getY () < stopHeight : # switch direction ( dx , dy ) = getShift ( center , pt ) ( dx , dy ) = ( dx * calibration , dy * calibration ) else : #NEW get out from depths of the loop return #NEW shape . move ( dx , dy ) time . sleep ( delay )
Call back that a return
statement immediately terminates function execution. In this case the function returns no value, only a blank return
is legal to force the exit. Since the testing is not washed in the normal while
condition, the while
status is set as permanently True
. This is non the most common while
loop pattern! It obscures the loop exit. The selection between the arroyo of bounce3.py
and bounce4.py
is a matter of sense of taste in the given state of affairs.
[i] | "while ___", "do ___ while", "repeat while", "repeat until", "as long as ___, exercise", "keep doing ___ as long as" |
[2] | Yous will need a loop. Y'all can print/append about all the numbers in the loop. You are likely to omit one number with just this lawmaking, just after looking at what y'all produce, it is easy to separately include the remaining number. At that place are several ways to exercise this. |
[3] | Recall the congenital-in len role! It applies to lists. |
[four] | The basic issue is similar to the old version: the undraw is non always needed – at the beginning in this instance. In this place it is not needed the first time through the loop. The ii bones approaches considered for the previous version nonetheless work here: make an extra compensating activity outside the loop or interruption into cases inside the loop. Further hint: It is legal to draw a polygon with an empty vertex list - nothing appears on the screen. |
Source: http://anh.cs.luc.edu/handsonPythonTutorial/whilestatements.html
0 Response to "Whenever I Loop Again the Numbers Just Add"
Post a Comment