id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
10,400 | def addpick(cuedictionary)from madlib py '''prompt for user response using the cue stringand place the cue-response pair in the dictionary ''promptformat "enter specific example for {name}prompt promptformat format(name=cueresponse input(promptdictionary[cueresponse def getuserpicks(cues)'''loop through the collection of cue keys and get user choices return the resulting dictionary ''userpicks dict(for cue in cuesaddpick(cueuserpicksreturn userpicks def tellstory(storyformat)'''storyformat is string with python dictionary references embeddedin the form {cueprompt the user for the mad lib substitutions and then print the resulting story with the substitutions ''cues getkeys(storyformatuserpicks getuserpicks(cuesstory storyformat format(**userpicksprint(storydef main()originalstoryformat ''once upon timedeep in an ancient junglethere lived {animalthis {animalliked to eat {food}but the jungle had very little {foodto offer one dayan explorer found the {animaland discovered it liked {foodthe explorer took the {animalback to {city}where it could eat as much {foodas it wanted howeverthe {animalbecame homesickso the explorer brought it back to the jungleleaving large supply of {foodthe end ''tellstory(originalstoryformatinput("press enter to end the program "main(does the use of well-named functions make it easier to follow this codewe have broken the large overall problem into many smaller steps make sure you follow the flow of execution and data and see how all the pieces fit together mad libs revisited |
10,401 | substring locations exercise rename the example file locationsstub py to be locations pyand complete the function printlocationsto print the index of each location in the string where target is located for exampleprintlocations('this is dish''is'would go through the string 'this is dishlooking for the index of places where 'isappearsand would print similarly printlocations('this is dish'' 'would print the program stub already uses the string method count you will need to add code using the more general form of find graphics graphics make programming more fun for many people to fully introduce graphics would involve many ideas that would be distraction now this section introduces simplified graphics module developed by john zelle for use with his python programming book my slight elaboration of his package is graphics py in the example programs warningyou need the file graphics py in the same folder as any graphics program you write be sure to save any graphics program you write in such folder (like my examples folderthe easiest way to ensure this is to start in the desired folderas discussed in starting idle for editing (page warningto work on the most systemsthis version of graphics py cannot be used from the idle shell there is an issue with the use of multiple threads of execution graphics introduction noteyou will just be user of the graphics py codeso you do not need to understand the inner workingsit uses all sorts of features of python that are way beyond these tutorials there is no particular need to open graphics py in the idle editor load into idle and start running example graphintrosteps pyor start running from the operating system folder each time you press returnlook at the screen and read the explanation for the next line(spress returnfrom graphics import win graphwin( objects and methods |
10,402 | zelle' graphics are not part of the standard python distribution for the python interpreter to find zelle' moduleit must be imported the first line above makes all the types of object of zelle' module accessibleas if they were already defined like built-in types str or list look around on your screenand possibly underneath other windowsthere should be new window labeled "graphics window"created by the second line bring it to the topand preferably drag it around to make it visible beside your shell window graphwin is type of object from zelle' graphics package that automatically displays window when it is created the assignment statement remembers the window object as win for future reference (this will be our standard name for our graphics window object small window by pixels is created pixel is the smallest little square that can by displayed on your screen modern screen usually have more than pixels across the whole screen press returnpt point( this creates point object and assigns it the name pt unlike when graphwin is creatednothing is immediately displayedin theory you could have more than one graphwin zelle designed the graphics module so you must tell python into which graphwin to draw the point point objectlike each of the graphical objects that can be drawn on graphwinhas method draw press returnpt draw(winnow you should see the point if you look hard in the graphics window it shows as singlesmallblack pixel graphics windows have cartesian ( ,ycoordinate system the dimensions are initially measured in pixels the first coordinate is the horizontal coordinatemeasured from left to rightso is about half way across the pixel wide window the second coordinatefor the vertical directionincreases going down from the top of the window by defaultnot up as you are likely to expect from geometry or algebra class the coordinate out of the total vertically should be about / of the way down from the top we will see later that we can reorient the coordinate system to fit our taste henceforth you will see draw method call after each object is createdso there is something to see press returncir circle(pt cir draw(winthe first line creates circle object with center at the previously defined pt and with radius this object is remembered with the name cir as with all graphics objects that may be drawn within graphwinit is only made visible by explicitly using its draw method so fareverything has been drawn in the default color black graphics objects like circle have methods to change their colors basic color name strings are recognized you can choose the color for the circle outline as well as filling in the inside press returncir setoutline('red'cir setfill('blue'note the method names they can be used with other kinds of graphics objectstoo (we delay discussion of fancier colors until color names (page and custom colors (page press return the basic ideas of objects and methods were introduced in object orientation (page graphics |
10,403 | line line(ptpoint( )line draw(wina line object is constructed with two points as parameters in this case we use the previously named pointptand specify another point directly technically the line object is segment between the the two points warningin python ( is tuplenot point to make pointyou must use the full constructorpoint( pointsnot tuplesmust be used in the constructors for all graphics objects rectangle is also specified by two points the points must be diagonally opposite corners press returnrect rectangle(point( )ptrect draw(winin this simple systema rectangle is restricted to have horizontal and vertical sides polygonintroduced in the next sectionis used for all more general straight-sided shapes you can move objects around in graphwin shortly this will be handy for animation the parameters to the move method are the amount to shift the and coordinates see if you can guess the result before you press returnline move( did you remember that the coordinate increases down the screentake your last look at the graphics windowand make sure that all the steps make sense then destroy the window win with the graphwin method close press returnwin close(the example program graphintro py starts with the same graphics code as graphintosteps pybut without the need for pressing returns an addition have made to zelle' package is the ability to print string value of graphics objects for debugging purposes if some graphics object isn' visible because it is underneath something else of off the screentemporarily adding this sort of output might be good reality check at the end of graphintro pyi added print lines to illustrate the debugging possibilitiesprint('cir:'cirprint('line:'lineprint('rect:'rectyou can load graphintro py into idlerun itand add further lines to experiment if you like of course you will not see their effect until you run the whole programunfortunately the graphics do not work when entered directly into the shell sample graphics programs in graphintro pya prompt to end the graphics program appeared in the shell windowrequiring you to pay attention to two windows instead consider very simple example programface pywhere all the action takes place in the graphics window the only interaction is to click the mouse to close the graphics window objects and methods |
10,404 | in windowshave folder window open to the python examples folder containing face pywhere your operating system setup may allow you be just double click on the icon for face py to run it if that does not work on your systemyou can always run from inside idle after you have checked out the pictureclick with the mouse inside the pictureas requestedto terminate the program after you have run the programyou can examine the program in idle or look below the whole program is shown firstsmaller pieces of it are discussed later''' simple graphics example constructs face from basic shapes ''from graphics import def main()win graphwin('face' give title and dimensions win yup(make right side up coordinateshead circle(point( , ) set center and radius head setfill("yellow"head draw(wineye circle(point( ) eye setfill('blue'eye draw(wineye line(point( )point( )set endpoints eye setwidth( eye draw(winmouth oval(point( )point( )set corners of bounding box mouth setfill("red"mouth draw(winlabel text(point( )' face'label draw(winmessage text(point(win getwidth()/ )'click anywhere to quit 'message draw(winwin getmouse(win close(main(let us look at individual parts until further notice the set-off code is for you to read and have explained from graphics import immediately after the documentation stringalways have the import line in your graphics programto allow easy access to the graphics py module win graphwin('face' give title and dimensions win yup(make right side up coordinatesthe first line shows the more general parameters for constructing new graphwina window title plus width and height in pixels the second line shows how to turn the coordinate system right-side-upso the coordinate increases up the screenusing the yup method (this is one of my additions to zelle' graphics thereafterall coordinates are graphics |
10,405 | given in the new coordinate system all the lines of code up to this point in the program are my standard graphics program starting lines (other than the specific values for the title and dimensionsyou will likely start your programs with similar code head circle(point( , ) set center and radius head setfill('yellow'head draw(wineye circle(point( ) eye setfill('blue'eye draw(winthe lines above create two circlesin each case specifying the centers directly they are filled in and made visible also notethat because the earlier win yup call put the coordinates in the normal orientationthe coordinate and are above the middle of the pixel high window if the code was switched to put the head part secondthe eye would become hidden the most recent thing drawn is on top eye line(point( )point( )set endpoints eye setwidth( eye draw(winthe code above draws and displays lineand illustrates another method available to graphics objectsetwidthmaking thicker line mouth oval(point( )point( )set corners of bounding box mouth setfill('red'mouth draw(winthe code above illustrates another kind of graphics objectan oval (or ellipsethere are several ways an oval could be specified zelle chose to have you specify the corners of the bounding box that is just as high and as wide as the oval this rectangle is only imaginednot actually drawn (if you want to see such rectanglecreate rectangle object with the same two points as parameters label text(point( )' face'label draw(winthe code above illustrates how text object is used to place text on the window the parameters to construct the text object are the point at the center of the textand the text string itself the exact coordinates for the parts were determined by number of trial-and-error refinements to the program an advantage of graphics is that you can see the results of your programmingand make changes if you do not like the resultsin this simple systemthere is not good way to predict the dimensions of text on the screen the final action is to have the user signal to close the window just as with waiting for keyboard input from inputit is important to prompt the user before waiting for responsein graphwinthat means using prompt must be made with text object displayed explicitly before the response is expected message text(point(win getwidth()/ )'click anywhere to quit 'message draw(winwin getmouse(win close(the new addition to the text parameters here is win getwidth(to obtain the window width (there is also win getheight(using win getwidth()/ means the horizontal position is set up to be centeredhalf way across the window' width after the first two lines draw the prompting textthe line win getmouse(waits for mouse click in this programthe position of the mouse click is not important (in the next example the position of this mouse click will be used objects and methods |
10,406 | as you have seen beforewin close(closes the graphics window while our earlier text-based python programs have automatically terminated after the last line finishes executingthat is not true for programs that create new windowsthe graphics window must be explicitly closed the win close(is necessary we will generally want to prompt the user to finally close the graphics window because such sequence is so commoni have added another method for zelle' graphwin objectspromptcloseso the last four lines can be reduced to win promptclose(win getwidth()/ where the only specific data needed is the coordinates of the center of the prompt the modified program is in face py you can copy the form of this program for other simple programs that just draw picture the size and title on the window will changeas well as the specific graphical objectspositionsand colors something like the last line can be used to terminate the program warningif you write program with bugand the program bombs out while there is graphwin on the screena dead graphwin lingers the best way to clean things up is to make the shell window be the current window and select from the menu shell restart shell another simple drawing example is balloons py feel free to run it and look at the code in idle note that the steps for the creation of all three balloons are identicalexcept for the location of the center of each balloonso loop over list of the centers makes sense the next exampletriangle pyillustrates similar starting and ending code in addition it explicitly interacts with the user rather than the code specifying literal coordinates for all graphical objectsthe program remembers the points where the user clicked the mouse they are used as the vertices of triangle return to the directory window for the python examples in windows you may be able to double click on the icon for triangle py to run it or on macyou can run it using the python launcherrather than idle while running the programfollow the prompts in the graphics window and click with the mouse as requested after you have run the programyou can examine the program in idle or look below'''programtriangle py or triangle pyw (best name for windowsinteractive graphics program to draw trianglewith prompts in text object and feedback via mouse clicks ''from graphics import def main()win graphwin('draw triangle' win yup(right side up coordinates win setbackground('yellow'message text(point(win getwidth()/ )'click on three points'message settextcolor('red'message setstyle('italic'message setsize( message draw(winget and draw three vertices of triangle win getmouse( draw(winp win getmouse( draw(winp win getmouse( graphics |
10,407 | draw(winvertices [ use polygon object to draw the triangle triangle polygon(verticestriangle setfill('gray'triangle setoutline('cyan'triangle setwidth( width of boundary line triangle draw(winmessage settext('click anywhere to quit'change text message win getmouse(win close(main(let us look at individual parts the lines before the new linewin setbackground('yellow'are standard starting lines (except for the specific values chosen for the widthheightand titlethe background color is property of the whole graphics window that you can set message text(point(win getwidth()/ )'click on three points'message settextcolor('red'message setstyle('italic'message setsize( message draw(winagain text object is created this is the prompt for user action these lines illustrate most of the ways the appearance of text object may be modifiedwith results like in most word processors the reference pages for graphics py give the details this reference is introduced shortly in the documentation for graphics py (page after the promptthe program looks for responseget and draw three vertices of triangle win getmouse( draw(winp win getmouse( draw(winp win getmouse( draw(winthe win getmouse(method (with no parameters)waits for you to click the mouse inside win then the point where the mouse was clicked is returned in this code three mouse clicks are waited forremembered in variables and and the points are drawn next we introduce very versatile type of graphical objecta polygonwhich may have any number of vertices specified in list as its parameter we see that the methods setfill and setoutline that we used earlier on circleand the setwidth method we used for linealso apply to polygon(and also to other graphics objectsvertices [ triangle polygon(verticestriangle setfill('gray'triangle setoutline('cyan' objects and methods |
10,408 | triangle setwidth( triangle draw(winbesides changing the style of text objectthe text itself may be changedmessage settext('click anywhere to quit'then lines responding to this promptwin getmouse(win close(if you want to use an existing text object to display the quitting promptas did herei provide variation on my window closing method that could replace the last three lineswin promptclose(messagean existing text object may be given as parameter rather than coordinates for new text object the complete code with that substitution is in triangle py if you want to make regular polygons or starsyou need some trigonometrynot required for this tutorialbut you can see its use in example polygons py windows operating system specializationpyw this windows-specific section is not essential it does describe how to make some windows graphical programs run with less clutter if you ran the triangle py program by double clicking its icon under windowsyou might have noticed console window first appearingfollowed by the graphics window for this programthere was no keyboard input or screen output through the console windowso the console window was unused and unnecessary in such casesunder windowsyou can change the source file extension from py to pywsuppressing the display of the console window if you are using windowschange the filename triangle py to triangle pywdouble click on the icon in its directory folderand check it out the distinction is irrelevant inside idlewhich always has its shell window graphics py vs event driven graphics this optional section only looks forward to more elaborate graphics systems than are used in this tutorial one limitation of the graphics py module is that it is not robust if graphics window is closed by clicking on the standard operating system close button on the title bar if you close graphics window that wayyou are likely to get python error message on the other handif your program creates graphics window and then terminates abnormally due to some other errorthe graphics window may be left orphaned in this case the close button on the title bar is importantit is the easiest method to clean up and get rid of the windowthis lack of robustness is tied to the simplification designed into the graphics module modern graphics environments are event driven the program can be interrupted by input from many sources including mouse clicks and key presses this style of programming has considerable learning curve in zelle' graphics packagethe complexities of the event driven model are pretty well hidden if the programmer wants user inputonly one type can be specified at time (either mouse click in the graphics window via the getmouse methodor via the input keyboard entry methods into the shell window graphics |
10,409 | the documentation for graphics py thus far various parts of zelle' graphics package have been introduced by example systematic reference to zelle' graphics package with the form of all function calls is at concepts and methods one special graphics input object typeentrywill be discussed later you might skip it for now another section of the reference that will not be pursued in the tutorials is the image class meanwhile you can look at attention to the organization of the referencemost graphics object share number of common methods those methods are described togetherfirst thenunder the headings for specific typesonly the specialized additional methods are discussed the version for this tutorial has few elaborations here is all their documentation togethergraphwin method yup ( increases upwardwhen you first create graphwinthe coordinates increase down the screen to reverse to the normal orientation use my graphwin yup method win graphwin('right side up' win yup(graphwin method promptclose (prompt and close graphics windowyou generally want to continue displaying your graphics window until the user chooses to have it closed the graphwin promptclose method posts promptwaits for mouse clickand closes the graphwin there are two ways to call itdepending on whether you want to use an existing text objector just specify location for the center of the prompt win promptclose(win getwidth()/ specify xy coordinates of prompt or msg text(point( )'original message 'msg draw(winjust important that there is drawn text object win promptclose(msguse existing text object string representations of all graphics object types each graphical type can be converted to string or printedand descriptive string is produced (for debugging purposesit only shows positionnot other parts of the state of the object pt point( print(ptpoint( ln line(ptpoint( )print(lnline(point( )point( )scene exercise make program scene py creating scene with the graphics methods you are likely to need to adjust the positions of objects by trial and error until you get the positions you want make sure you have graphics py in the same directory as your program objects and methods |
10,410 | changing scene exercise elaborate the scene program above so it becomes changescene pyand changes one or more times when you click the mouse (and use win getmouse()you may use the position of the mouse click to affect the resultor it may just indicate you are ready to go on to the next view issues with mutable objects zelle chose to have the constructor for rectangle take diagonally opposite corner points as parameters suppose you prefer to specify only one corner and also specify the width and height of the rectangle you might come up with the following functionmakerectto return such new rectangle read the following attemptdef makerect(cornerwidthheight)'''return new rectangle given one corner point and the dimensions ''corner corner corner move(widthheightreturn rectangle(cornercorner the second corner must be created to use in the rectangle constructorand it is done above in two steps start corner from the given corner and shift it by the dimensions of the rectangle to the other corner with both corners specifiedyou can use zelle' version of the rectangle constructor unfortunately this is an incorrect argument run the example program makerectbad py'''programmakerectbad py attempt function makerect (incorrectly)which takes takes corner point and dimensions to construct rectangle ''from graphics import def makerect(cornerwidthheight)incorrect'''return new rectangle given one corner point and the dimensions ''corner corner corner move(widthheightreturn rectangle(cornercorner def main()win graphwin('draw rectangle (not!)' win yup(rect makerect(point( ) rect draw(winwin promptclose(win getwidth()/ main(by stated designthis program should draw rectangle with one corner at the point ( , and the other corner at ( + , + or the point ( , )and so the rectangle should take up most of the by window when you run it however that is not what you see look carefully you should just see one point toward the upper right cornerwhere the second corner should be since rectangle was being drawnit looks like it is the tiniest of rectangleswhere the opposite corners are at the same pointhmwell the program did make the corners be the same initially recall we set corner corner what happens after that graphics |
10,411 | read and follow the details of what happens we need to take much more careful look at what naming an object means good way to visualize this association between name and an object is to draw an arrow from the name to the object associated with it the object here is pointwhich has an and coordinate describing its stateso when the makerect method is started the parameter name corner is associated with the actual parametera point with coordinates ( nextthe assignment statement associates the name corner with the same object it is another nameor aliasfor the original point the next linecorner move(widthheightinternally changes or mutates the point objectand since in this case width is and height is the coordinates of the point associated with the name corner change to + = and + = lookthe name corner is still associated with the same objectbut that object has changed internallythat is the problemwe wanted to keep the name corner associated with the point with original coordinatesbut it has been modified the solution is to use the clone method that is defined for all the graphical objects in graphics py it creates separate objectwhich is copy with an equivalent state we just need to change the line corner corner to objects and methods |
10,412 | corner corner clone( diagram of the situation after the cloning isthough corner and corner refer to points with equivalent coordinatesthey do not refer to the same object then after corner move(widthheightwe getno conflictcorner and corner refer to the corners we want makerectangle py run the corrected example programmore on mutable and immutable types read this section if you want deeper understanding of the significance of mutable and immutable objects this alias problem only came up because point is mutable we had no such problems with the immutable types int or str read and follow the discussion of the following code just for comparisonconsider the corresponding diagrams for code with ints that looks superficially similara after the first two lines we have an alias again graphics |
10,413 | the third line does not change the int object the result of the addition operation refers to different object and the name is assigned to ithence is still associated with the integer no conflict it is not technically correct to think of as being the number and then but little sloppiness of thought does not get you in trouble with immutable types with mutable typeshoweverbe very careful of aliases then it is very important to remember the indirectnessthat name is not the same thing as the object it refers to another mutable type is list list can be cloned with the slice notation[:try the following in the shell nums [ numsalias nums numsclone nums[:nums append( numsalias append( nums numsalias numsclone animation run the example programbackandforth py the whole program is shown below for convenience then each individual new part of the code is discussed individually'''test animation and depth ''from graphics import import time actuallylists are even trickierbecause individual elements of list may be mutableeach mutable element in the cloned list is an alias of the corresponding element in the original listso if you mutate its state in the cloned listyou also make change to the original list this is distinct from the situation if you replace an element in the cloned list by totally different onethen you do not change the original list objects and methods |
10,414 | def main()win graphwin('back and forth' win yup(make right side up coordinatesrect rectangle(point( )point( )rect setfill("blue"rect draw(wincir circle(point( , ) cir setfill("yellow"cir draw(wincir circle(point( , ) cir setfill("red"cir draw(winfor in range( )cir move( time sleep for in range( )cir move(- time sleep win promptclose(win getwidth()/ main(read the discussion below of pieces of the code from the program above do not try to execute fragments alone there are both an old and new form of import statementfrom graphics import import time the program uses function from the time module the syntax used for the time module is actually the safer and more typical way to import module as you will see later in the programthe sleep function used from the time module will be referenced as time sleep(this tells the python interpreter to look in the time module for the sleep function if we had used the import statement from time import then the sleep function could just be referenced with sleep(this is obviously easierbut it obscures the fact that the sleep function is not part of the current module also several modules that program imports might have functions with the same name with the individual module name prefixthere is no ambiguity hence the form import modulename is actually safer than from modulename import you might think that all modules could avoid using any of the same function names with bit of planning to get an idea of the magnitude of the issuehave look at the number of modules available to python try the following in the in the shell (and likely wait number of seconds)help('modules'without module names to separate things outit would be very hard to totally avoid name collisions with the enormous number of modules you see displayedthat are all available to pythonback to the current example programthe main program starts with standard window creationand then makes three objects graphics |
10,415 | rect rectangle(point( )point( )rect setfill('blue'rect draw(wincir circle(point( , ) cir setfill('yellow'cir draw(wincir circle(point( , ) cir setfill('red'cir draw(winzelle' reference pages do not mention the fact that the order in which these object are first drawn is significant if objects overlapthe ones which used the draw method later appear on top other object methods like setfill or move do not alter which are in front of which this becomes significant when cir moves the moving cir goes over the rectangle and behind cir (run the program again if you missed that the animation starts with the code for simple repeat loopfor in range( )cir move( time sleep animate cir to the right this very simple loop animates cir moving in straight line to the right as in moviethe illusion of continuous motion is given by jumping only short distance each time (increasing the horizontal coordinate by the time sleep functionmentioned earliertakes as parameter time in seconds to have the program sleepor delaybefore continuing with the iteration of the loop this delay is importantbecause modern computers are so fastthat the intermediate motion would be invisible without the delay the delay can be given as decimalto allow the time to be fraction of second the next three lines are almost identical to the previous linesand move the circle to the left (- in the horizontal coordinate each timefor in range( )animate cir to the left cir move(- time sleep the next example programbackandforth pyit just slight variationlooking to the user just like the last version only the small changes are shown below this version was written after noticing how similar the two animation loops aresuggesting an improvement to the programanimating any object to move in straight line is logical abstraction well expressed via function the loop in the initial version of the program contained number of arbitrarily chosen constantswhich make sense to turn into parameters alsothe object to be animated does not need to be cir it can be any of the drawable objects in the graphics package the name shape is used to make this parameterdef moveonline(shapedxdyrepetitionsdelay)for in range(repetitions)shape move(dxdytime sleep(delaythen in the main function the two similar animation loops are reduced to line for each directionmoveonline(cir moveonline(cir - make sure you see these two lines with function calls behave the same way as the two animation loops in the main program of the original version objects and methods |
10,416 | run the next example versionbackandforth py the changes are more substantial hereand the display of the whole program is followed by display and discussion of the individual changes'''test animation of group of objects making face ''from graphics import import time def moveall(shapelistdxdy)''move all shapes in shapelist by (dxdy''for shape in shapelistshape move(dxdydef moveallonline(shapelistdxdyrepetitionsdelay)'''animate the shapes in shapelist along line move by (dxdyeach time repeat the specified number of repetitions have the specified delay (in secondsafter each repeat ''for in range(repetitions)moveall(shapelistdxdytime sleep(delaydef main()win graphwin('back and forth' win yup(make right side up coordinatesrect rectangle(point( )point( )rect setfill("blue"rect draw(winhead circle(point( , ) head setfill("yellow"head draw(wineye circle(point( ) eye setfill('blue'eye draw(wineye line(point( )point( )eye setwidth( eye draw(winmouth oval(point( )point( )mouth setfill("red"mouth draw(winfacelist [headeye eye mouthcir circle(point( , ) cir setfill("red"cir draw(winmoveallonline(facelist moveallonline(facelist- graphics |
10,417 | win promptclose(win getwidth()/ main(read the following discussion of program parts moving single elementary shape is rather limiting it is much more interesting to compose more complicated combinationlike the face from the earlier example face py to animate such combinationyou cannot use the old moveonline functionbecause we want all the parts to move togethernot one eye all the way across the screen and then have the other eye catch upa variation on moveonline is needed where all the parts move together we need all the parts of the face to move one stepthen sleep onceand all move againsleep oncethis could all be coded in single methodbut there are really two ideas here moving group of objects one step animating number of moves for the group this suggests two functions another issue is how to handle group of elementary graphics objects the most basic combination of objects in python is listso we assume parameter shapelistwhich is list of elementary graphics objects for the first functionmovealljust move all the objects in the list one step since we assume list of objects and we want to move eachthis suggests for-each loopdef moveall(shapelistdxdy)''move all shapes in shapelist by (dxdy''for shape in shapelistshape move(dxdyhaving this functionwe can easily write the second function moveallonlinewith simple change from the moveonline functionsubstituting the moveall function for the line with the move methoddef moveallonline(shapelistdxdyrepetitionsdelay)'''animate the shapes in shapelist along line move by (dxdyeach time repeat the specified number of repetitions have the specified delay (in secondsafter each repeat ''for in range(repetitions)moveall(shapelistdxdytime sleep(delaythe code in main to construct the face is the same as in the earlier example face py once all the pieces are constructed and coloredthey must be placed in listfor use in moveallonlinefacelist [headeye eye mouththenlaterthe animation uses the facelist to make the face go back and forthmoveallonline(facelist moveallonline(facelist- this version of the program has encapsulated and generalized the moving and animating by creating functions and adding parameters that can be substituted againmake sure you see how the functions communicate to make the whole program work this is an important and non-trivial use of functions in fact all parts of the face do not actually move at oncethe moveall loop code moves each part of the face separatelyin sequence depending on your computer setupall the parts of the face may appear to move together againthe computer is much faster than our eyes on computer that repaints the screen fast enoughthe only images we notice are the ones on the screen when the animation is sleeping objects and methods |
10,418 | noteon fast enough computer you can make many consecutive changes to an image before the next sleep statementand they all appear to happen at once in the animation optional refinementnot all computers are set up for the same graphics speed in python one machine that use animates backandforth py quite well another seems to have the mouth wiggle on the latter sort of machineduring animation it is useful not to have visible screen changes for every individual move instead you can explicitly tell the computer when it is the right time to redraw the screen the computer can store changes and then update the screen withholding updates is controlled by win autoflush it starts as truebut can be changed to false before animation when set to falseyou must call update(every time you want the screen refreshed that is going to be just before the time sleep(in an animation in backandforth update py this is illustratedwith moveallonline replaced by moveallonlineupdate#new update versionadded win param def moveallonlineupdate(shapelistdxdyrepetitionsdelaywin)'''animate the shapes in shapelist along line in win move by (dxdyeach time repeat the specified number of repetitions have the specified delay (in secondsafter each repeat ''win autoflush false newset before animation for in range(repetitions)moveall(shapelistdxdyupdate(new needed to make all the changes appear time sleep(delaywin autoflush true newset after animation run the next example program backandforth py the final versionbackandforth py and its variantbackandforth update pyuse the observation that the code to make face embodies one unified ideasuggesting encapsulation inside function once you have encapsulated the code to make facewe can make several facesthen the problem with the original code for the face is that all the positions for the facial elements are hard-codedthe face can only be drawn in one position the full listing of backandforth py below includes makeface function with parameter for the position of the center of the face beneath the listing of the whole program is discussion of the individual changes'''test animation of group of objects making face combine the face elements in functionand use it twice have an extra level of repetition in the animation this version may be wobbly and slow on some machinesthen see backandforthflush py ''from graphics import import time def moveall(shapelistdxdy)''move all shapes in shapelist by (dxdy''for shape in shapelistshape move(dxdydef moveallonline(shapelistdxdyrepetitionsdelay)'''animate the shapes in shapelist along line graphics |
10,419 | move by (dxdyeach time repeat the specified number of repetitions have the specified delay (in secondsafter each repeat ''for in range(repetitions)moveall(shapelistdxdytime sleep(delaydef makeface(centerwin)'''display face centered at center in window win return list of the shapes in the face ''head circle(center head setfill("yellow"head draw(wineye center center clone(face positions are relative to the center eye center move(- locate further points in relation to others eye circle(eye center eye setfill('blue'eye draw(wineye end eye center clone(eye end move( eye end eye end clone(eye end move( eye line(eye end eye end eye setwidth( eye draw(winmouthcorner center clone(mouthcorner move(- - mouthcorner mouthcorner clone(mouthcorner move( - mouth oval(mouthcorner mouthcorner mouth setfill("red"mouth draw(winreturn [headeye eye mouthdef main()win graphwin('back and forth' win yup(make right side up coordinatesrect rectangle(point( )point( )rect setfill("blue"rect draw(winfacelist makeface(point( )winfacelist makeface(point( , )winstepsacross dx dy objects and methods |
10,420 | wait for in range( )moveallonline(facelistdx stepsacrosswaitmoveallonline(facelist-dxdystepsacross// waitmoveallonline(facelist-dx-dystepsacross// waitwin promptclose(win getwidth()/ main(read the following discussion of program parts as mentioned abovethe face construction function allows parameter to specify where the center of the face is the other parameter is the graphwin that will contain the face def makeface(centerwin)then the head is easily drawnusing this centerrather than the previous cir with its specific center point ( )head circle(center head setfill('yellow'head draw(winfor the remaining points used in the construction there is the issue of keeping the right relation to the center this is accomplished much as in the creation of the second corner point in the makerectangle function in section issues with mutable objects (page clone of the original center point is madeand then moved by the difference in the positions of the originally specified points for instancein the original facethe center of the head and first eye were at ( and ( respectively that means shift between the two coordinates of (- )since - - and - eye center center clone(face positions are relative to the center eye center move(- locate further points in relation to others eye circle(eye center eye setfill('blue'eye draw(winthe only other changes to the face are similarcloning and moving pointsrather than specifying them with explicit coordinates eye end eye center clone(eye end move( eye end eye end clone(eye end move( eye line(eye end eye end eye setwidth( eye draw(winmouthcorner center clone(mouthcorner move(- - mouthcorner mouthcorner clone(mouthcorner move( - mouth oval(mouthcorner mouthcorner mouth setfill('red'mouth draw(winfinallythe list of elements for the face must be returned to the caller graphics |
10,421 | return [headeye eye mouththen in the main functionthe program creates face in exactly the same place as beforebut using the makeface functionwith the original center of the face point( as parameter now with the makeface functionwith its center parameterit is also easy to replace the old cir with whole facefacelist makeface(point( )winfacelist makeface(point( , )winthe animation section is considerably elaborated in this version stepsacross dx dy wait for in range( )moveallonline(facelistdx stepsacrosswaitmoveallonline(facelist-dxdystepsacross// waitmoveallonline(facelist-dx-dystepsacross// waitthe unidentified numeric literals that were used before are replaced by named values that easily identify the meaning of each one this also allows the numerical values to be stated only onceallowing easy modification the whole animation is repeated three times by the use of simple repeat loop since moveallonline has for-loop inside itit illustrates nesting of loops the animations in the loop body illustrate that the straight line of motion does not need to be horizontal the second and third lines use non-zero value of both dx and dy for the stepsand move diagonally make sure you see now how the whole program works togetherincluding all the parameters for the moves in the loop by the waythe documentation of the functions in module you have just run in the shell is directly available try in the shellhelp(moveallnose in face exercise save backandforth py or backandforth update py to the new name backandforth py add triangular nose in the middle of the face in the makeface function like the other features of the facemake sure the position of the nose is relative to the center parameter make sure the nose is included in the final list of elements of the face that get returnedfaces exercise make program faces py that asks the user to click the mouseand then draws face at the point where the user clicked copy the makeface function definition from the previous exerciseand use itelaborate this with simple repeat loop (page )so this is repeated six timesafter each of mouse clicksa face immediately appears at the location of the latest click think how you can reuse your code each time through the loopmoving faces exercise animate two faces moving in different directions at the same time in program move faces py you cannot use the moveallonline function you will have to make variation of your own you can use the moveall function separately for each face objects and methods |
10,422 | hintimagine the old way of making an animated cartoon if each face was on separate piece of paperand you wanted to animate them moving togetheryou would place them separatelyrecord one framemove them each bit toward each otherrecord another framemove each another bit toward each otherrecord another framein our animations "record frameis replaced by short sleep to make the position visible to the user make loop to incorporate the repetition of the moves entry objects (optional sectionread this section if you want to allow the user to enter text directly into graphics window when using graphics windowthe shell window is still available keyboard input can be done in the normal text fashionwaiting for responseand going on after the user presses the enter key it is annoying to make user pay attention to two windowsso the graphics module provides way to enter text inside graphics windowwith the entry type the entry is partial replacement for the input function run the simple examplegreet pywhich is copied below"""simple example with entry objects enter your nameclick the mouseand see greetings ""from graphics import def main()win graphwin("greeting" win yup(instructions text(point(win getwidth()/ )"enter your name \nthen click the mouse "instructions draw(winentry entry(point(win getwidth()/ ), entry draw(wintext(point(win getwidth()/ ),'name:'draw(winlabel for the entry win getmouse(to know the user is finished with the text name entry gettext(greeting 'helloname '!text(point(win getwidth()/ )greeting draw(wingreeting 'bonjourname '!text(point( *win getwidth()/ )greeting draw(winwin promptclose(instructionsmain(the only part of this with new ideas isentry entry(point(win getwidth()/ ), entry draw(wintext(point(win getwidth()/ ),'name:'draw(winlabel for the entry win getmouse(to know the user is finished with the text name entry gettext( graphics |
10,423 | the first line of this excerpt creates an entry objectsupplying its center point and number of characters to leave space for ( in this caseas with other places where input is requesteda separate static label is added the way the underlying events are hidden in graphics pythere is no signal when the user is done entering text in an entry box to signal the programa mouse press is used above in this case the location of the mouse press is not relevantbut once the mouse press is processedexecution can go on and read the entry text the method name gettext is the same as that used with text object run the next exampleaddentries pyalso copied below"""example with two entry objects and type conversion do addition ""from graphics import def main()win graphwin("addition" win yup(instructions text(point(win getwidth()/ )"enter two numbers \nthen click the mouse "instructions draw(winentry entry(point(win getwidth()/ ), entry settext(' 'entry draw(wintext(point(win getwidth()/ ),'first number:'draw(winentry entry(point(win getwidth()/ ), entry settext(' 'entry draw(wintext(point(win getwidth()/ ),'second number:'draw(winwin getmouse(to know the user is finished with the text numstr entry gettext(num int(numstr numstr entry gettext(num int(numstr sum num num result "the sum of\ {num }\nplus\ {num }\nis {sumformat(**locals()text(point(win getwidth()/ )resultdraw(winwin promptclose(instructionsmain(as with the input statementyou can only read strings from an entry with conversionsit is still possible to work with numbers only one new graphical method has been included above objects and methods |
10,424 | entry settext(' 'again the same method name is used as with text object in this case chose not to leave the entry initially blank the value also reinforces that numerical value is expected there is also an entry with almost identical code after waiting for mouse clickboth entries are readand the chosen names emphasizes they are strings the strings must be converted to integers in order to do arithmetic and display the result the almost identical code for the two entries is strong suggestion that this code could be written more easily with function you may look at the identically functioning example program addentries py the only changes are shown below first there is function to create an entry and centered static label over it def makelabeledentry(entrycenterptentrywidthinitialstrlabeltextwin)'''return an entry object with specified centerwidth in charactersand initial string value also create static label over it with specified text draw everything in the graphwin win ''entry entry(entrycenterptentrywidthentry settext(initialstrentry draw(winlabelcenter entrycenterpt clone(labelcenter move( text(labelcenter,labeltextdraw(winreturn entry in case want to make more entries with labels laterand refer to this code againi put some extra effort inmaking things be parameters even if only one value is used in this program the position of the label is made units above the entry by using the clone and move methods only the entry is returnedon the assumption that the label is staticand once it is drawni can forget about it since do not refer later to the text objecti do not bother to name itbut just draw it immediately then the corresponding change in the main function is just two calls to this functionentry makelabeledentry(point(win getwidth()/ ) ' ''first number:'winentry makelabeledentry(point(win getwidth()/ ) ' ''second number:'winthese lines illustrate that statement may take more than one line in particularas in the shellpython is smart enough to realize that there must be continuation line if the parentheses do not match while was improving thingsi also changed the conversions to integers in the first version wanted to emphasize the existence of both the string and integer data as teaching pointbut the num str and num str variables were only used onceso more concise way to read and convert the values is to eliminate themnum int(entry gettext()num int(entry gettext()color names thus far we have only used common color names in fact there are very large number of allowed color namesand also the ability to draw with custom colors firstthe graphics package is built on an underlying graphics systemtkinterwhich has large number of color names defined each of the names can be used by itselflike 'red''salmonor 'aquamarineor with lower intensity by specifying with trailing number or like 'red for dark red graphics |
10,425 | though the ideas for the coding have not all been introducedit is still informative to run the example program colors py as you click the mouse over and overyou see the names and appearances of wide variety of built-in color names the names must be place in quotesbut capitalization is ignored custom colors custom colors can also be created to do that requires some understanding of human eyes and color (and the python toolsthe only colors detected directly by the human eyes are redgreenand blue each amount is registered by different kind of cone cell in the retina as far as the eye is concernedall the other colors we see are just combinations of these three colors this fact is used in color video screensthey only directly display these three colors common scale to use in labeling the intensity of each of the basic colors (redgreenblueis from to with meaning none of the colorand being the most intense hence color can be described by sequence of redgreenand blue intensities (often abbreviated rgbthe graphics package has functioncolor_rgbto create colors this way for instance color with about half the maximum red intensityno greenand maximum blue intensity would be acolor color_rgb( such creation can be used any place color is used in the graphics( circle setfill(acolor)random colors another interesting use of the color_rgb function is to create random colors randomcircles py the code also is hererun example program """draw random circles ""from graphics import import randomtime def main()win graphwin("random circles" for in range( ) random randrange( random randrange( random randrange( color color_rgb(rgbradius random randrange( random randrange( random randrange( circle circle(point( , )radiuscircle setfill(colorcircle draw(wintime sleep win promptclose(win getwidth()/ main(read the fragments of this program and their explanationsto do random thingsthe program needs function from the random module this example shows that imported modules may be put in comma separated list objects and methods |
10,426 | import randomtime you have already seen the built-in function range to generate sequence of all the integers you would use range( this is the full list of possible values for the redgreen or blue intensity parameter for this program we randomly choose any one element from this sequence instead of the range functionuse the random module' randrange functionas in random randrange( random randrange( random randrange( color color_rgb(rgbthis gives randomly selected values to each of rgand bwhich are then used to create the random color want random circle radiusbut do not want number as small as making it invisible the range and randrange functions both refer to possible sequence of values starting with when single parameter is used it is also possible to add different starting value as the first parameter you still must specify value past the end of the sequence for instance range( would refer to the sequence (starting with and not quite reaching similarly random randrange( randomly selects an arbitrary element of range( use the two-parameter version to select random parameters for circleradius random randrange( random randrange( random randrange( circle circle(point( , )radiuswhat are the smallest and largest values allow for and random values are often useful in games ranges exercise write program ranges py in three parts (test after each added part this problem is not graphics program it is just regular text program to illustrate your understanding of ranges and loops for simplicity each of the requested number sequences can just be printed with one number per line print label for each number sequence before you print the sequencelike numbers - numbers -nfive random numbers in - first use the range function and for-loop to produce the sequence and then print the numbersone number per line prompt the user to input an integer and print the sequence including nusing for-loop hint and (one less than if or is the last numberwhat is the first number past the end of the sequence graphics |
10,427 | use simple repeat loop (page to find and print five randomly chosen numbers from the range use the same value of that the user chose earlier in the program it should be possible that the number is printed sometimes text triangle exercise write program texttriangle py thistoois not graphics program prompt the user for small positive integer valuethat 'll call then use for-loop with range function call to make triangular arrangement of '#'characterswith '#characters in the last line hint then leave blank line then make similar triangleexcept start with the line with '#characters to make the second triangleyou can use for-loop of the form discussed so farbut that is trickier than looking ahead to the most general range function (page and using for-loop where range function call has negative step size here is the screen after posible run with user input enter small positive integer ############and another possible run with user input enter small positive integer ## files this section fits here logically (as an important built-in type of objectbut it is not needed for the next more on flow of control (page thus far you have been able to save programsbut anything produced during the execution of program has been lost when the program ends data has not persisted past the end of execution just as programs live on in filesyou can generate and read data files in python that persist after your program has finished running as far as python is concerneda file is just string (often very large!stored on your file systemthat you can read or writegradually or all together directory is an old name for folder these ideas go back far enough to the time before directories got graphical folder representation for this section we use the word directory to mean the same thing as folder row of '#characters is easiest if you remember the string multiplication operator objects and methods |
10,428 | writing files open directory window for your python program directory first note that there is no file named sample txt make sure you have started idle so the current directory is your python program directory run the example program firstfile pyshown belowoutfile open('sample txt'' 'outfile write('my first output file!'outfile close(the first line creates file objectwhich links python to your computer' file system the first parameter in the file constructor gives the file namesample txt the second parameter indicates how you use the file the 'wis short for writeso you will be creating and writing to file warningif the file already existedthe old contents are destroyed if you do not use any operating system directory separators in the name ('\or '/depending on your operating system)then the file will lie in the current directory the assignment statement gives the python file object the name outfile the second line writes the specified string to the file the last line is important to clean up until this linethis python program controls the fileand nothing may be actually written to an operating system file yetsince initiating file operation is thousands of times slower than memory operationspython buffers datasaving small amounts and writing larger chunk all at once warningthe close line is essential for python to make sure everything is really writtenand to relinquish control of the file it is common bug to write program where you have the code to add all the data you want to filebut the program does not end up creating file usually this means you forgot to close the file now switch focus and look at directory window for the current directory you should now see file sample txt you can open it in idle (or your favorite word processorand see its contents for the next examplerun the example program nextfile pyshown belowwhich has two calls to the write methodoutfile open('sample txt'' 'outfile write('my second output file!'outfile write('write some more 'outfile close(now look at the filesample txt open it in idle it may not be what you expectthe write method for the file is not quite like print function it does not add anything to the file except exactly the data you tell it to write if you want newlineyou must indicate it explicitly recall the newline code '\nrun the example program revisedfile pyshown belowwhich adds newline codesoutfile open('sample txt'' 'outfile write(' revised output file!\ 'outfile write('write some more \ 'outfile close(check the contents of sample txt files |
10,429 | reading files run the example program printfile pyshown below'''quick illustration of reading file (needs revisedfile py run first to create sample txt''infile open('sample txt'' 'contents infile read(print(contentsnow you have come full circlewhat one python program has written into the file sample txtanother has read and displayed in the first line of the program an operating system file (sample txtis associated again with python variable name (infilethe second parameter again gives the mode of operationbut this time it is ' 'short for read this filesample txtshould already existand the intention is to read from it this is the most common mode for fileso the 'rparameter is actually optional the read method returns all the file' data as single stringhere assigned to the variable contents using the close method is generally optional with files being read there is nothing to lose if program ends without closing file that was being read notethere are three related but distinct concepts related to files beginners often get confused and try to merge several in their head or substitute one for another the file name is string that identifies the file in your computer' file system you need the file name to open file creating file objectbut the file object (that tend to call infile or outfileis not the same as the name of the file on your hard drive you assign it to variable name just for use inside your program there is still one more step to the most important partthe contents of the file the read method for file object reads and returns existing contentwhile the write method writes new content into the file there are other methods to read just parts of files (that you can look up in the python documentation)but for this tutorialreading the whole file with the read method is sufficient printupper exercise make the following programs in sequence be sure to save the programs in the same directory as where you start the idle shortcut and where you have all the sample text files printupper pyread the contents of the sample txt file and print the contents out in upper case (this should use file operations and should work no matter what the contents are in sample txt do not assume the particular string written by nextfile py! fileupper pyprompt the user for file nameread and print the contents of the requested file in upper case copyfileupper pymodify fileupper py to write the upper case contents string to new file rather than printing it have the name of the new file be dynamically derived from the old name by prepending 'upperto the name for exampleif the user specified the file sample txt (from above)the program would create file uppersample txtcontaining 'my first output file!when the user specifies the file name stuff txtthe resulting file would be named upperstuff txt iffor some reasonyou want to reread this same file while the same program is runningyou need to close it and reopen it objects and methods |
10,430 | mad lib file exercise write madlib pya small modification of madlib pyrequiring only modification to the main function of madlib py (even better is to start from madlib py if you did the exercise in unique list exercise (page )also create file mymadlib txtas described below your madlib py should prompt the user for the name of file that should contain madlib format string as text (with no quotes around itread in this file and use it as the format string in the tellstory function this is unlike in madlib pywhere the story is literal string coded directly into the programassigned to the variable originalstory the tellstory function and particularly the getkeys function were developed and described in detail in this tutorialbut for this exercise there is no need to follow their inner workings you are just user of the tellstory function (and the functions that it callsyou do not need to mess with the code for the definition of tellstory or any of the earlier supporting functions just keep them from the copy you made of madlib py for your madlib py the original madlib string is already placed in file jungle txt as an example of the story file format expected with the idle editorwrite another madlib format string into file mymadlib txt if you earlier created program mymadlib pythen you can easily extract the story from there (without the quotes around ittest your program madlib py twiceusing jungle txt and then your new madlib story file mymadlib txt summary the same typographical conventions will be used as in the summary (page object notation (awhen the name of type of object is used as function callit is called constructorand new object of that type is constructed and implicitly returned (no return statementthe meanings of any parameters to the constructor depend on the type [constructors (page )(bobject methodnameparameters objects have special operations associated with themcalled methods they are functions automatically applied to the object before the dot further parameters may be expecteddepending on the particular method [object orientation (page ) string (strindexing and methods see the summary (page for string literals and symbolic string operations (astring indexing [string indices (page )stringreference intexpression individual characters in string may be chosen if the string has length lthen the indices start from for the initial character and go to - for the rightmost character negative indices may also be used to count from the right end- for the rightmost character through - for the leftmost character strings are immutableso individual characters may be readbut not set (bstring slices [string slices (page )stringreference start pastend stringreference pastend stringreference start stringreference summary |
10,431 | substring or slice of or more consecutive characters of string may be referred to by specifying starting index and the index one past the last character of the substring if the starting or ending index is left out python uses and the length of the string respectively python assumes indices that would be beyond an end of the string actually mean the end of the string (cstring methodsassume refers to string upper(returns an uppercase version of the string [object orientation (page )ii lower(returns lowercase version of the string [object orientation (page )iii countsub returns the number of repetitions of the substring sub inside [object orientation (page )iv findsub findsub start findsub start end returns the index in of the first character of the first occurrence of the substring sub within the part of the string indicatedrespectively the whole string sor sstart ]or sstart end ]where start and end have integer values [object orientation (page ) split( splitsep the first version splits at any sequence of whitespace (blanksnewlinestabsand returns the remaining parts of as list if string sep is specifiedit is the separator that gets removed from between the parts of the list [split (page )vi sep joinsequence return new string obtained by joining together the sequence of strings into one stringinterleaving the string sep between sequence elements [join (page )vii further string methods are discussed in the python reference manualin the section on built-in types [further exploration (page ) sets set is collection of elements with no repetitions it can be used as sequence in for loop set constructor can take any other sequence as parameterand convert the sequence to set (with no repetitionsnonempty set literals are enclosed in braces [sets (page ) list method append alist appendelement add an arbitrary element to the end of the list alistmutating the listnot returning any list [appending to list (page ) files [files (page )(aopennameinfilesystem opennameinfilesystem 'rreturns file object for readingwhere nameinfilesystem must be string referring to an existing file (bopennameinfilesystem ' ' objects and methods |
10,432 | returns file object for writingwhere the string nameinfilesystem will be the name of the file if it did not exist beforeit is created if it did exist beforeall previous contents are erased (cif infile is file opened for readingand outfile is file opened for writingthen infile read(returns the entire file contents of the file as string infile close(closes the file in the operating system (generally not neededunless the file is going to be modified laterwhile your program is still runningoutfile writestringexpression writes the string to the filewith no extra newline outfile close(closes the file in the operating system (important to make sure the whole file gets written and to allow other access to the file mutable objects [issues with mutable objects (page )care must be taken whenever second name is assigned to mutable object it is an alias for the original nameand refers to the exact same object mutating method applied to either name changes the one object referred to by both names many types of mutable object have ways to make copy that is distinct object zelle' graphical objects have the clone method copy of list may be made with full slicesomelist[:then direct mutations to one list (like appending an elementdo not affect the other listbut stilleach list is indirectly changed if common mutable element in the lists is changed graphics systematic reference to zelle' graphics packagegraphics pyis at (aintroductory examples of using graphics py are in [ graphics introduction (page )][sample graphics programs (page )]and [entry objects (page )(bwindows operating system pyw in windowsa graphical program that take no console input and generates no console outputmay be given the extension pyw to suppress the generation of console window [ windows operating system specializationpyw (page )(cevent-driven programs graphical programs are typically event-drivenmeaning the next operation done by the program can be in response to large number of possible operationsfrom the keyboard or mouse for instancewithout the program knowing which kind of event will come next for simplicitythis approach is pretty well hidden under zelle' graphics packageallowing the illusion of simpler sequential programming [graphics py vs event driven graphics (page )(dcustom computer colors are expressed in terms of the amounts of redgreenand blue [custom colors (page )(esee also animation under the summary of programming techniques additional programming techniques these techniques extend those listed in the summary (page of the previous (asophisticated operations with substrings require careful setting of variables used as an index [index variables (page ) summary |
10,433 | (bthere are number of techniques to assist creative programmingincluding pseudo-code and gradual generalization from concrete examples [creative problem solving steps (page )(canimationa loop involving small moves followed by short delay (assumes the time module is imported)[animation (page )loop heading move all objects small step in the proper direction time sleepdelay (dexample of practical successive modification loop[ function to ease the creation of mad libs (page )(eexamples of encapsulating ideas in functions and reusing them[ function to ease the creation of mad libs (page )][the revised mad lib program (page )][animation (page )(frandom results can be introduced into program using the random module [random colors (page ) objects and methods |
10,434 | three more on flow of control you have varied the normal forward sequence of operations with functions and for loops to have full power over your programsyou need two more constructions that changing the flow of controldecisions choosing between alternatives (if statements)and more general loops that are not required to be controlled by the elements of collection (while loops if statements simple conditions the statements introduced in this will involve tests or conditions more syntax for conditions will be introduced laterbut for now consider simple arithmetic comparisons that directly translate from math into python try each line separately in the shell type(trueyou see that conditions are either true or false these are the only possible boolean values (named after th century mathematician george boolein python the name boolean is shortened to the type bool it is the type of the results of true-false conditions or tests notethe boolean values true and false have no quotes around themjust as ' is string and without the quotes is not'trueis stringnot of type bool simple if statements run this example programsuitcase py try it at least twicewith inputs and then as you an seeyou get an extra resultdepending on the input the main code isweight float(input("how many pounds does your suitcase weigh")if weight print("there is $ charge for luggage that heavy "print("thank you for your business "the middle two line are an if statement it reads pretty much like english if it is true that the weight is greater than then print the statement about an extra charge if it is not true that the weight is greater than then don' do |
10,435 | the indented partskip printing the extra luggage charge in any eventwhen you have finished with the if statement (whether it actually does anything or not)go on to the next statement that is not indented under the if in this case that is the statement printing "thank youthe general python syntax for simple if statement is if condition indentedstatementblock if the condition is truethen do the indented statements if the condition is not truethen skip the indented statements another fragment as an exampleif balance transfer -balance transfer enough from the backup accountbackupaccount backupaccount transfer balance balance transfer as with other kinds of statements with heading and an indented blockthe block can have more than one statement the assumption in the example above is that if an account goes negativeit is brought back to by transferring money from backup account in several steps in the examples above the choice is between doing something (if the condition is trueor nothing (if the condition is falseoften there is choice of two possibilitiesonly one of which will be donedepending on the truth of condition if-else statements run the example programclothes py try it at least twicewith inputs and then as you can seeyou get different resultsdepending on the input the main code of clothes py istemperature float(input('what is the temperature')if temperature print('wear shorts 'elseprint('wear long pants 'print('get some exercise outside 'the middle four lines are an if-else statement again it is close to englishthough you might say "otherwiseinstead of "else(but else is shorter!there are two indented blocksonelike in the simple if statementcomes right after the if heading and is executed when the condition in the if heading is true in the if-else form this is followed by an elselinefollowed by another indented block that is only executed when the original condition is false in an if-else statement exactly one of two possible indented blocks is executed line is also shown dedented nextremoving indentationabout getting exercise since it is dedentedit is not part of the if-else statementsince its amount of indentation matches the if headingit is always executed in the normal forward flow of statementsafter the if-else statement (whichever block is selectedthe general python if-else syntax is if condition indentedstatementblockfortruecondition elseindentedstatementblockforfalsecondition these statement blocks can have any number of statementsand can include about any kind of statement see graduate exercise (page more on flow of control |
10,436 | more conditional expressions all the usual arithmetic comparisons may be madebut many do not use standard mathematical symbolismmostly for lack of proper keys on standard keyboard meaning less than greater than less than or equal greater than or equal equals not equal math symbol <>python symbols <>=!there should not be space between the two-symbol python substitutes notice that the obvious choice for equalsa single equal signis not used to check for equality an annoying second equal sign is required this is because the single equal sign is already used for assignment in pythonso it is not available for tests warningit is common error to use only one equal sign when you mean to test for equalityand not make an assignmenttests for equality do not make an assignmentand they do not require variable on the left any expressions can be tested for equality or inequality (!=they do not need to be numberspredict the results and try each line in the shellx = = ! = ! 'hi=' ' 'hi!'hi[ ![ an equality check does not make an assignment strings are case sensitive order matters in list try in the shell' when the comparison does not make sensean exception is caused following up on the discussion of the inexactness of float arithmetic in string formats for float precision (page )confirm that python does not consider to be equal to write simple condition into the shell to test here is another examplepay with overtime given person' work hours for the week and regular hourly wagecalculate the total pay for the weektaking into account overtime hours worked over are overtimepaid at times the normal rate this is natural place for function enclosing the calculation read the setup for the functiondef calcweeklywages(totalhourshourlywage)'''return the total weekly wages for worker working totalhours this is an improvement that is new in python if statements |
10,437 | with given regular hourlywage ''include overtime for hours over the problem clearly indicates two caseswhen no more than hours are worked or when more than hours are worked in case more than hours are workedit is convenient to introduce variable overtimehours you are encouraged to think about solution before going on and examining mine you can try running my complete example programwages pyalso shown below the format operation at the end of the main function uses the floating point format (string formats for float precision (page )to show two decimal places for the cents in the answerdef calcweeklywages(totalhourshourlywage)'''return the total weekly wages for worker working totalhourswith given regular hourlywage include overtime for hours over ''if totalhours < totalwages hourlywage*totalhours elseovertime totalhours totalwages hourlywage* ( *hourlywage)*overtime return totalwages def main()hours float(input('enter hours worked')wage float(input('enter dollars paid per hour')total calcweeklywages(hourswageprint('wages for {hourshours at ${wage fper hour are ${total fformat(**locals())main(here the input was intended to be numericbut it could be decimal so the conversion from string was via floatnot int below is an equivalent alternative version of the body of calcweeklywagesused in wages py it uses just one general calculation formula and sets the parameters for the formula in the if statement there are generally number of ways you might solve the same problemif totalhours < regularhours totalhours overtime elseovertime totalhours regularhours return hourlywage*regularhours ( *hourlywage)*overtime the in boolean operatorthere are also boolean operators that are applied to types others than numbers useful boolean operator is inchecking membership in sequencevals ['this''is''it'isin vals true 'wasin vals false it can also be used with notas not into mean the oppositevals ['this''is''it'isnot in vals false more on flow of control |
10,438 | 'wasnot in vals true in general the two versions areitem in sequence item not in sequence detecting the need for if statementslike with planning programs needing''for'statementsyou want to be able to translate english descriptions of problems that would naturally include if or if-else statements what are some words or phrases or ideas that suggest the use of these statementsthink of your own and then compare to few gave graduate exercise write programgraduate pythat prompts students for how many credits they have print whether of not they have enough credits for graduation (at loyola university chicago credits are needed for graduation head or tails exercise write program headstails py it should include function flip()that simulates single flip of coinit randomly prints either heads or tails accomplish this by choosing or arbitrarily with random randrange( )and use an if-else statement to print heads when the result is and tails otherwise in your main program have simple repeat loop that calls flip( times to test itso you generate random sequence of heads and tails strange function exercise save the example program jumpfuncstub py as jumpfunc pyand complete the definitions of functions jump and main as described in the function documentation strings in the program in the jump function definition use an if-else statement (hint in the main function definition use for-each loopthe range functionand the jump function the jump function is introduced for use in strange sequence exercise (page )and others after that multiple tests and if-elif statements often you want to distinguish between more than two distinct casesbut conditions only have two possible resultstrue or falseso the only direct choice is between two options as anyone who has played " questionsknowsyou can distinguish more cases by further questions if there are more than two choicesa single test may only reduce the possibilitiesbut further tests can reduce the possibilities further and further since most any kind of statement can be placed in an indented statement blockone choice is further if statement for instance consider function to convert numerical grade to letter grade' '' '' ''dor ' 'where the cutoffs for ' '' '' 'and 'dare and respectively one way to write the function would be test for one grade at timeand resolve all the remaining possibilities inside the next else clause "in this case do ___otherwise""if ___then""when ___ is truethen""___ depends on whether" if you divide an even number by what is the remainderuse this idea in your if condition if statements |
10,439 | def lettergrade(score)if score > letter 'aelsegrade must be bcd or if score > letter 'belsegrade must be cd or if score > letter 'celsegrade must or if score > letter 'delseletter 'freturn letter this repeatedly increasing indentation with an if statement as the else block can be annoying and distracting preferred alternative in this situationthat avoids all this indentationis to combine each else and if block into an elif blockdef lettergrade(score)if score > letter 'aelif score > letter 'belif score > letter 'celif score > letter 'delseletter 'freturn letter the most elaborate syntax for an if-elif-else statement is indicated in general belowif condition indentedstatementblockfortruecondition elif condition indentedstatementblockforfirsttruecondition elif condition indentedstatementblockforfirsttruecondition elif condition indentedstatementblockforfirsttruecondition elseindentedstatementblockforeachconditionfalse the ifeach elifand the final else lines are all aligned there can be any number of elif lineseach followed by an indented block (three happen to be illustrated above with this construction exactly one of the indented blocks is executed it is the one corresponding to the first true conditionorif all conditions are falseit is the block after the final else line be careful of the strange python contraction it is elifnot elseif program testing the lettergrade function is in example program grade py see grade exercise (page final alternative for if statementsif-elifwith no else this would mean changing the syntax for ifelif-else above so the final elseand the block after it would be omitted it is similar to the basic if statement more on flow of control |
10,440 | without an elsein that it is possible for no indented block to be executed this happens if none of the conditions in the tests are true with an else includedexactly one of the indented blocks is executed without an elseat most one of the indented blocks is executed if weight print('sorrywe can not take suitcase that heavy 'elif weight print('there is $ charge for luggage that heavy 'this if-elif statement only prints line if there is problem with the weight of the suitcase sign exercise write program sign py to ask the user for number print out which category the number is in'positive''negative'or 'zerograde exercise in idleload grade py and save it as grade py modify grade py so it has an equivalent version of the lettergrade function that tests in the opposite orderfirst for fthen dchinthow many tests do you need to do be sure to run your new version and test with different inputs that test all the different paths through the program be careful to test around cut-off points what does grade of implywhat about exactly wages exercise modify the wages py or the wages py example to create program wages py that assumes people are paid double time for hours over hence they get paid for at most hours overtime at times the normal rate for examplea person working hours with regular wage of $ per hour would work at $ per hour for hoursat $ for hours of overtimeand $ for hours of double timefor total of * * * * * $ you may find wages py easier to adapt than wages py be sure to test all paths through the programyour program is likely to be modification of program where some choices worked beforebut once you change thingsretest for all the caseschanges can mess up things that worked before nesting control-flow statements the power of language like python comes largely from the variety of ways basic statements can be combined in particularfor and if statements can be nested inside each other' indented blocks for examplesuppose you want to print only the positive numbers from an arbitrary list of numbers in function with the following heading read the pieces for now def printallpositive(numberlist)'''print only the positive numbers in numberlist '' tests to distinguish the casesas in the previous version if statements |
10,441 | for examplesuppose numberlist is [ - - you want to process listso that suggests for-each loopfor num in numberlistbut for-each loop runs the same code body for each element of the listand we only want print(numfor some of them that seems like major obstaclebut think closer at what needs to happen concretely as humanwho has eyes of amazing capacityyou are drawn immediately to the actual correct numbers and but clearly computer doing this systematically will have to check every number in factthere is consistent action requiredevery number must be tested to see if it should be printed this suggests an if statementwith the condition num try loading into idle and running the example program onlypositive pywhose code is shown below it ends with line testing the functiondef printallpositive(numberlist)'''print only the positive numbers in numberlist ''for num in numberlistif num print(numprintallpositive([ - - ]this idea of nesting if statements enormously expands the possibilities with loops now different things can be done at different times in loopsas long as there is consistent test to allow choice between the alternatives shortlywhile loops will also be introducedand you will see if statements nested inside of themtoo the rest of this section deals with graphical examples run example program bounce py it has red ball moving and bouncing obliquely off the edges if you watch several timesyou should see that it starts from random locations also you can repeat the program from the shell prompt after you have run the script for instanceright after running the programtry in the shell bounceball(- the parameters give the amount the shape moves in each animation step you can try other values in the shellpreferably with magnitudes less than for the remainder of the description of this exampleread the extracted text pieces the animations before this were totally scriptedsaying exactly how many moves in which directionbut in this case the direction of motion changes with every bounce the program has graphic object shape and the central animation step is shape move(dxdybut in this casedx and dy have to change when the ball gets to boundary for instanceimagine the ball getting to the left side as it is moving to the left and up the bounce obviously alters the horizontal part of the motionin fact reversing itbut the ball would still continue up the reversal of the horizontal part of the motion means that the horizontal shift changes direction and therefore its signdx -dx but dy does not need to change this switch does not happen at each animation stepbut only when the ball reaches the edge of the window it happens only some of the time suggesting an if statement still the condition must be determined suppose the center of the ball has coordinates (xywhen reaches some particular coordinatecall it xlowthe ball should bounce more on flow of control |
10,442 | the edge of the window is at coordinate but xlow should not be or the ball would be half way off the screen before bouncingfor the edge of the ball to hit the edge of the screenthe coordinate of the center must be the length of the radius awayso actually xlow is the radius of the ball animation goes quickly in small stepsso cheat allow the ball to take one (smallquickstep past where it really should go (xlow)and then we reverse it so it comes back to where it belongs in particular if xlowdx -dx there are similar bounding variables xhighylow and yhighall the radius away from the actual edge coordinatesand similar conditions to test for bounce off each possible edge note that whichever edge is hitone coordinateeither dx or dyreverses one way the collection of tests could be written is if xlowdx -dx if xhighdx -dx if ylowdy -dy if yhighdy -dy this approach would cause there to be some extra testingif it is true that xlowthen it is impossible for it to be true that xhighso we do not need both tests together we avoid unnecessary tests with an elif clause (for both and )if xlowdx -dx elif xhighdx -dx if ylowdy -dy elif yhighdy -dy note that the middle if is not changed to an elifbecause it is possible for the ball to reach cornerand need both dx and dy reversed the program also uses several methods to read part of the state of graphics objects that we have not used in examples yet various graphics objectslike the circle we are using as the shapeknow their center pointand it can be accessed with the getcenter(method (actually clone of the point is returned also each coordinate of point can be accessed with the getx(and gety(methods this explains the new features in the central function defined for bouncing around in boxbounceinbox the animation arbitrarily goes on in simple repeat loop for steps ( later example will improve this behavior def bounceinbox(shapedxdyxlowxhighylowyhigh)''animate shape moving in jumps (dxdy)bouncing when its center reaches the low and high and coordinates ''delay for in range( )shape move(dxdy if statements |
10,443 | center shape getcenter( center getx( center gety(if xlowdx -dx elif xhighdx -dx if ylowdy -dy elif yhighdy -dy time sleep(delaythe program starts the ball from an arbitrary point inside the allowable rectangular bounds this is encapsulated in utility function included in the programgetrandompoint the getrandompoint function uses the randrange function from the module random note that in parameters for both the functions range and randrangethe end stated is past the last value actually desireddef getrandompoint(xlowxhighylowyhigh)'''return random point with coordinates in the range specified '' random randrange(xlowxhigh+ random randrange(ylowyhigh+ return point(xythe full program is listed belowrepeating bounceinbox and getrandompoint for completeness several parts that may be useful lateror are easiest to follow as unitare separated out as functions make sure you see how it all hangs together or ask questions''show ball bouncing off the sides of the window ''from graphics import import timerandom def bounceinbox(shapedxdyxlowxhighylowyhigh)''animate shape moving in jumps (dxdy)bouncing when its center reaches the low and high and coordinates ''delay for in range( )shape move(dxdycenter shape getcenter( center getx( center gety(if xlowdx -dx elif xhighdx -dx if ylowdy -dy elif yhighdy -dy time sleep(delaydef getrandompoint(xlowxhighylowyhigh)'''return random point with coordinates in the range specified '' random randrange(xlowxhigh+ more on flow of control |
10,444 | random randrange(ylowyhigh+ return point(xydef makedisk(centerradiuswin)'''return red disk that is drawn in win with given center and radius ''disk circle(centerradiusdisk setoutline("red"disk setfill("red"disk draw(winreturn disk def bounceball(dxdy)'''make ball bounce around the screeninitially moving by (dxdyat each jump ''win graphwin('ball bounce' win yup(radius xlow radius center is separated from the wall by the radius at bounce xhigh win getwidth(radius ylow radius yhigh win getheight(radius center getrandompoint(xlowxhighylowyhighball makedisk(centerradiuswinbounceinbox(balldxdyxlowxhighylowyhighwin close(bounceball( short string exercise write program short py with function printshort with headingdef printshort(strings)'''given list of stringsprint the ones with at most three characters printshort([' ''long'one'] one ''in your main programtest the functioncalling it several times with different lists of strings hintfind the length of each string with the len function the function documentation here models common approachillustrating the behavior of the function with python shell interaction this part begins with line starting with other exercises and examples will also document behavior in the shell even print exercise write program even py with function printeven with headingdef printeven(nums)'''given list of integers nums if statements |
10,445 | print the even ones printeven([ ] ''in your main programtest the functioncalling it several times with different lists of integers hinta number is even if its remainderwhen dividing by is even list exercise write program even py with function chooseeven with headingdef chooseeven(nums)'''given list of integersnumsreturn list containing only the even ones chooseeven([ ][ ''in your main programtest the functioncalling it several times with different lists of integers and printing the results in the main program (the documentation string illustrates the function call in the python shellwhere the return value is automatically printed rememberthat in programyou only print what you explicitly say to print hintin the functioncreate new listand append the appropriate numbers to itbefore returning the result unique list exercise the madlib py program has its getkeys functionwhich first generates list of each occurrence of cue in the story format this gives the cues in orderbut likely includes repetitions the original version of getkeys uses quick method to remove duplicatesforming set from the list there is disadvantage in the conversionthoughsets are not orderedso when you iterate through the resulting setthe order of the cues will likely bear no resemblance to the order they first appeared in the list that issue motivates this problemcopy madlib py to madlib pyand add function with this headingdef uniquelist(alist)''return new list that includes the first occurrence of each value in alistand omits later repeats the returned list should include the first occurrences of values in alist in their original order vals ['cat''dog''cat''bug''dog''ant''dog''bug'uniquelist(vals['cat''dog''bug''ant'''hintprocess alist in order use the in syntax to only append elements to new list that are not already in the new list after perfecting the uniquelist functionreplace the last line of getkeysso it uses uniquelist to remove duplicates in keylist check that your madlib py prompts you for cue values in the order that the cues first appear in the madlib format string more on flow of control |
10,446 | compound boolean expressions to be eligible to graduate from loyola university chicagoyou must have credits and gpa of at least this translates directly into python as compound conditioncredits > and gpa >= this is true if both credits > is true and gpa > is true short example program using this would becredits float(input('how many units of credit do you have')gpa float(input('what is your gpa')if credits > and gpa >= print('you are eligible to graduate!'elseprint('you are not eligible to graduate 'the new python syntax is for the operator andcondition and condition the compound condition is true if both of the component conditions are true it is false if at least one of the conditions is false see congress exercise (page in the last example in the previous sectionthere was an if-elif statement where both tests had the same block to be done if the condition was trueif xlowdx -dx elif xhighdx -dx there is simpler way to state this in sentenceif xhighswitch the sign of dx that translates directly into pythonif xhighdx -dx the word or makes another compound conditioncondition or condition is true if at least one of the conditions is true it is false if both conditions are false this corresponds to one way the word "oris used in english other times in english "oris used to mean exactly one alternative is true warningwhen translating problem stated in english using "or"be careful to determine whether the meaning matches python' or it is often convenient to encapsulate complicated tests inside function think how to complete the function startingdef isinside(rectpoint)'''return true if the point is inside the rectangle rect ''pt rect getp (pt rect getp (recall that rectangle is specified in its constructor by two diagonally oppose points this example gives the first use in the tutorials of the rectangle methods that recover those two corner pointsgetp and getp the if statements |
10,447 | program calls the points obtained this way pt and pt the and coordinates of pt pt and point can be recovered with the methods of the point typegetx(and gety(suppose that introduce variables for the coordinates of pt pointand pt calling these -coordinates end valand end respectively on first try you might decide that the needed mathematical relationship to test is end <val <end unfortunatelythis is not enoughthe only requirement for the two corner points is that they be diagonally oppositenot that the coordinates of the second point are higher than the corresponding coordinates of the first point it could be that end is end is and val is in this latter case val is between end and end but substituting into the expression above < < is false the and need to be reversed in this case this makes complicated situation also this is an issue which must be revisited for both the and coordinates introduce an auxiliary function isbetween to deal with one coordinate at time it startsdef isbetween(valend end )'''return true if val is between the ends the ends do not need to be in increasing order ''clearly this is true if the original expressionend <val <end is true you must also consider the possible case when the order of the ends is reversedend <val <end how do we combine these two possibilitiesthe boolean connectives to consider are and and or which appliesyou only need one to be trueso or is the proper connectivea correct but redundant function body would beif end <val <end or end <val <end return true elsereturn false check the meaningif the compound expression is truereturn true if the condition is falsereturn false in either case return the same value as the test condition see that much simpler and neater version is to just return the value of the condition itselfreturn end <val <end or end <val <end notein general you should not need an if-else statement to choose between true and false valuesoperate directly on the boolean expression side comment on expressions like end <val <end other than the two-character operatorsthis is like standard math syntaxchaining comparisons in python any number of comparisons can be chained in this wayclosely approximating mathematical notation though this is good pythonbe aware that if you try other high-level languages like java and ++such an expression is gibberish another way the expression can be expressed (and which translates directly to other languagesisend <val and val <end so much for the auxiliary function isbetween back to the isinside function you can use the isbetween function to check the coordinatesisbetween(point getx() getx() getx() more on flow of control |
10,448 | and to check the coordinatesisbetween(point gety() gety() gety()again the question ariseshow do you combine the two testsin this case we need the point to be both between the sides and between the top and bottomso the proper connector is and think how to finish the isinside method hint sometimes you want to test the opposite of condition as in english you can use the word not for instanceto test if point was not inside rectangle rectyou could use the condition not isinside(rectpointin generalnot condition is true when condition is falseand false when condition is true the example program choosebutton pyshown belowis complete program using the isinside function in simple applicationchoosing colors pardon the length do check it out it will be the starting point for number of improvements that shorten it and make it more powerful in the next section first brief overviewthe program includes the functions isbetween and isinside that have already been discussed the program creates number of colored rectangles to use as buttons and also as picture components aside from specific data valuesthe code to create each rectangle is the sameso the action is encapsulated in functionmakecoloredrect all of this is fineand will be preserved in later versions the present main function is longthough it has the usual graphics starting codedraws buttons and picture elementsand then has number of code sections prompting the user to choose color for picture element each code section has long if-elif-else test to see which button was clickedand sets the color of the picture element appropriately '''make choice of colors via mouse clicks in rectangles - demonstration of boolean operators and boolean functions ''from graphics import def isbetween(xend end )'''return true if is between the ends or equal to either the ends do not need to be in increasing order ''return end < <end or end < <end def isinside(pointrect)'''return true if the point is inside the rectangle rect ''pt rect getp (pt rect getp (return isbetween(point getx()pt getx()pt getx()and isbetween(point gety()pt gety()pt gety()def makecoloredrect(cornerwidthheightcolorwin)''return rectangle drawn in win with the upper left corner and color specified ''corner corner clone(corner move(width-height once againyou are calculating and returning boolean result you do not need an if-else statement if statements |
10,449 | rect rectangle(cornercorner rect setfill(colorrect draw(winreturn rect def main()win graphwin('pick colors' win yup(right side up coordinates redbutton makecoloredrect(point( ) 'red'winyellowbutton makecoloredrect(point( ) 'yellow'winbluebutton makecoloredrect(point( ) 'blue'winhouse makecoloredrect(point( ) 'gray'windoor makecoloredrect(point( ) 'white'winroof polygon(point( )point( )point( )roof setfill('black'roof draw(winmsg text(point(win getwidth()/ ),'click to choose house color 'msg draw(winpt win getmouse(if isinside(ptredbutton)color 'redelif isinside(ptyellowbutton)color 'yellowelif isinside(ptbluebutton)color 'blueelse color 'whitehouse setfill(colormsg settext('click to choose door color 'pt win getmouse(if isinside(ptredbutton)color 'redelif isinside(ptyellowbutton)color 'yellowelif isinside(ptbluebutton)color 'blueelse color 'whitedoor setfill(colorwin promptclose(msgmain(the only further new feature used is in the long return statement in isinside return isbetween(point getx()pt getx()pt getx()and isbetween(point gety()pt gety()pt gety()recall that python is smart enough to realize that statement continues to the next line if there is an unmatched pair of parentheses or brackets above is another situation with long statementbut there are no unmatched parentheses on line for readability it is best not to make an enormous long line that would run off your screen or paper more on flow of control |
10,450 | continuing to the next line is recommended you can make the final character on line be backslash ('\\'to indicate the statement continues on the next line this is not particularly neatbut it is rather rare situation most statements fit neatly on one lineand the creator of python decided it was best to make the syntax simple in the most common situation (many other languages require special statement terminator symbol like ';and pay no attention to newlinesextra parentheses here would not hurtso an alternative would be return (isbetween(point getx()pt getx()pt getx()and isbetween(point gety()pt gety()pt gety()the choosebutton py program is long partly because of repeated code the next section gives another version involving lists congress exercise person is eligible to be us senator who is at least years old and has been us citizen for at least years write an initial version of program congress py to obtain age and length of citizenship from the user and print out if person is eligible to be senator or not person is eligible to be us representative who is at least years old and has been us citizen for at least years elaborate your program congress py so it obtains age and length of citizenship and prints out just the one of the following three statements that is accurateyou are eligible for both the house and senate you eligible only for the house you are ineligible for congress more string methods here are few more string methods useful in the next exercisesassuming the methods are applied to string ss startswithpre returns true if string starts with string preboth '- startswith('-'and 'downstairsstartswith('down'are truebut ' startswith('-'is false endswithsuffix returns true if string ends with string suffixboth 'whoeverendswith('ever'and 'downstairsendswith('airs'are truebut ' endswith('-'is false replacesub replacement count returns new string with up to the first count occurrences of string sub replaced by replacement the replacement can be the empty string to delete sub for examples '- replace('-''' equals ' replace('-''' is still equal to ' replace(''' equals ' replace('dot ' equals ' dot dot dot if statements |
10,451 | article start exercise in library alphabetizingif the initial word is an article ("the"" ""an")then it is ignored when ordering entries write program completing this functionand then testing itdef startswitharticle(title)'''return true if the first word of title is "the""aor "an''be carefulif the title starts with "there"it does not start with an article what should you be testing foris number string exercise *in the later safe number input exercise (page )it will be important to know if string can be converted to the desired type of number explore that here save example isnumberstringstub py as isnumberstring py and complete it it contains headings and documentation strings for the functions in both parts of this exercise legal whole number string consists entirely of digits luckily strings have an isdigit methodwhich is true when nonempty string consists entirely of digitsso ' isdigit(returns trueand ' aisdigit(returns falseexactly corresponding to the situations when the string represents whole numberin both parts be sure to test carefully not only confirm that all appropriate strings return true also be sure to test that you return false for all sorts of bad strings recognizing an integer string is more involvedsince it can start with minus sign (or nothence the isdigit method is not enough by itself this part is the most straightforward if you have worked on the sections string indices (page and string slices (page an alternate approach works if you use the count method from object orientation (page )and some methods from this section complete the function isintstr complete the function isdecimalstrwhich introduces the possibility of decimal point (though decimal point is not requiredthe string methods mentioned in the previous part remain useful loops and tuples this section will discuss several improvements to the choosebutton py program from the last section that will turn it into example program choosebutton py first an introduction to tupleswhich we will use for the first time in this sectiona tuple is similar to list except that literal tuple is enclosed in parentheses rather than square bracketsand tuple is immutable in particular you cannot change the length or substitute elementsunlike list examples are ( ('yes''no'making tuple is another way to make several items into single object you can refer to individual parts with indexinglike with listsbut more common way is with multiple assignment silly simple exampletup ( (xytup print(xprints print(yprints now back to improving the choosebutton py programwhich has similar code repeating in several places imagine how much worse it would be if there were more colors to choose from and more parts to colorfirst consider the most egregious example more on flow of control |
10,452 | if isinside(ptredbutton)color 'redelif isinside(ptyellowbutton)color 'yellowelif isinside(ptbluebutton)color 'blueelse color 'whitenot only is this exact if statement repeated several timesall the conditions within the if statement are very similarpart of the reason did not put this all in function was the large number of separate variables on further inspectionthe particular variables redbuttonyellowbuttonbluebuttonall play similar roleand their names are not really importantit is their associations that are importantthat redbutton goes with 'red'when there is sequence of things all treated similarlyit suggests list and loop an issue here is that the changing data is paireda rectangle with color string there are number of ways to handle such associations very neat way in python to package pair (or more things togetheris tupleturning several things into one objectas in (redbuttton'red'objects such are this tuple can be put in larger listchoicepairs [(redbuttton'red')(yellowbutton'yellow')(bluebutton'blue')such tuples may be neatly handled in for statement you can imagine function to encapsulate the color choice startingdef getchoice(choicepairsdefaultwin)'''given list choicepairs of tupleswith each tuple in the form (rectanglechoice)return the choice that goes with the rectangle in win where the mouse gets clickedor return default if the click is in none of the rectangles ''point win getmouse(for (rectanglechoicein choicepairsthis is the first time we have had for loop going through list of tuples recall that we can do multiple assignments at once with tuples this also works in for loop heading the for loop goes through one tuple in the list choicepairs at time the first time through the loop the tuple taken from the list is (redbuttton'red'this for loop does multiple assignment to (rectanglechoiceeach time through the loopso the first time rectangle refers to redbutton and choice refers to 'redthe next time through the loopthe second tuple from the list is used(yellowbutton'yellow'so this time inside the loop rectangle will refer to yellowbutton and choice refers to 'yellowthis is neat python feature there is still problem we could test each rectangle in the for-each loopbut the original if-elif statement in choosebutton py stops when the first condition is true however for-each statements are designed to go all the way through the sequence there is simple way out of this in functiona return statement always stops the execution of function when we have found the rectangle containing the pointthe function can return the desired choice immediatelydef getchoice(choicepairsdefaultwin)'''given list of tuples (rectanglechoice)return the choice that goes with the rectangle in win where the mouse gets clickedor return default if the click is in none of the rectangles ''point win getmouse( particularly in other object-oriented languages where lists and tuples are way less easy to usethe preferred way to group associated objectslike rectangle and choiceis to make custom object type containing them all this is also possible and often useful in python in some relatively simple caseslike in the current exampleuse of tuples can be easier to followthough the approach taken is matter of taste the topic of creating custom type of objects will not be taken up in this tutorial loops and tuples |
10,453 | for (rectanglechoicein choicepairsif isinside(pointrectangle)return choice return default note that the else part in choosebutton py corresponds to the statement after the loop above if execution gets past the loopthen none of the conditions tested in the loop was true with appropriate parametersthe looping function is complete replacement for the original if-elif statementthe replacement has further advantages there can be an arbitrarily long list of pairsand the exact same code works this code is clearer and easier to readsince there is no need to read through long sequence of similar if-elif clauses the names of the rectangles in the tuples in the list are never referred to they are unnecessary here only list needs to be specified that could be useful earlier in the program are individual names for the rectangles needed earliernothe program only needs to end up with the pairs of the form (rectanglecolorin list the statements in the original programbelowhave similar form which will allow them to be rewrittenredbutton makecoloredrect(point( ) 'red'winyellowbutton makecoloredrect(point( ) 'yellow'winbluebutton makecoloredrect(point( ) 'blue'winas stated earlierwe could use the statements above and then make list of pairs with the statement choicepairs [(redbuttton'red')(yellowbutton'yellow')(bluebutton'blue')now will look at an alternative that would be particularly useful if there were considerably more buttons and colors all the assignment statements with makecolorrect have the same formatbut differing data for several parameters use that fact in the alternate codechoicepairs list(buttonsetup [( 'red')( 'yellow')( 'blue')for (xycolorin buttonsetupbutton makecoloredrect(point(xy) colorwinchoicepairs append((buttoncolor) extract the changing data from the creation of the rectangles into listbuttonsetup since more than one data items are different for each of the original linesthe list contains tuple of data from each of the original lines then loop through this list and not only create the rectangles for each colorbut also accumulates the (rectanglecolorpairs for the list choicepairs note the double parentheses in the last line of the code the outer ones are for the method call the inner ones create single tuple as the parameter assuming do not need the original individual names of the rectanglesthis code with the loop will completely substitute for the previous code with its separate lines with the separate named variables and the recurring formats this code has advantages similar to those listed above for the getchoice code now look at what this new code means for the interactive part of the program the interactive code directly reduces to msg text(point(win getwidth()/ ),'click to choose house color 'msg draw(wincolor getchoice(colorpairs'white'win more on flow of control |
10,454 | house setfill(colormsg settext('click to choose door color 'color getchoice(colorpairs'white'windoor setfill(colorin the original version with the long if-elif statementsthe interactive portion only included portions for the user to set the color of two shapes in the picture (or you would have been reading code foreverlooking now at the similarity of the code for the two partswe can imagine another loopthat would easily allow for many more parts to be colored interactively there are still several differences to resolve first the message msg is created the first timeand only the text is set the next time that is easy to make consistent by splitting the first part into an initialization and separate call to settext like in the second partmsg text(point(win getwidth()/ ),''msg draw(winmsg settext('click to choose house color 'then look to see the differences between the code for the two choices the shape object to be colored and the name used to describe the shape changetwo changes in each part again tuples can store the changes of the form (shapedescriptionthis is another place appropriate for loop driven by tuples the (shapedescriptiontuples should be explicitly written into list that can be called shapepairs we could easily extend the list shapepairs to allow more graphics objects to be colored in the code belowthe roof is added the new interactive code can start withshapepairs [(house'house')(door'door')(roof'roof')msg text(point(win getwidth()/ ),''msg draw(winfor (shapedescriptionin shapepairsprompt 'click to choose description color can you finish the body of the looplook at the original version of the interactive code when you are done thinking about itgo on to my solution the entire code is in example program choosebutton pyand also below the changes from choosebutton py are in three blockseach labeled #new in the code the new parts are the getchoice function and the two new sections of main with the loops'''make choice of colors via mouse clicks in rectangles -demonstate loops using lists of tuples of data ''from graphics import def isbetween(xend end )'''return true if is between the ends or equal to either the ends do not need to be in increasing order ''return end < <end or end < <end def isinside(pointrect)'''return true if the point is inside the rectangle rect ''pt rect getp (pt rect getp (return isbetween(point getx()pt getx()pt getx()and isbetween(point gety()pt gety()pt gety() loops and tuples |
10,455 | def makecoloredrect(cornerwidthheightcolorwin)''return rectangle drawn in win with the upper left corner and color specified ''corner corner clone(corner move(width-heightrect rectangle(cornercorner rect setfill(colorrect draw(winreturn rect def getchoice(choicepairsdefaultwin)#new '''given list choicepairs of tuples with each tuple in the form (rectanglechoice)return the choice that goes with the rectangle in win where the mouse gets clickedor return default if the click is in none of the rectangles ''point win getmouse(for (rectanglechoicein choicepairsif isinside(pointrectangle)return choice return default def main()win graphwin('pick colors' win yup(#new choicepairs list(buttonsetup [( 'red')( 'yellow')( 'blue')for (xycolorin buttonsetupbutton makecoloredrect(point(xy) colorwinchoicepairs append((buttoncolor)house makecoloredrect(point( ) 'gray'windoor makecoloredrect(point( ) 'white'winroof polygon(point( )point( )point( )roof setfill('black'roof draw(win#new shapepairs [(house'house')(door'door')(roof'roof')msg text(point(win getwidth()/ ),''msg draw(winfor (shapedescriptionin shapepairsprompt 'click to choose description color msg settext(promptcolor getchoice(choicepairs'white'winshape setfill(colorwin promptclose(msgmain(run it with the limited number of choices in choosebutton pythe change in length to convert to choosebutton py is not significantbut the change in organization is significant if you try to extend the pro more on flow of control |
10,456 | gramas in the exercise below see if you agreeexercises choose button exercise write program choosebutton pymodifying choosebutton py look at the format of the list buttonsetupand extend it so there is larger choice of buttons and colors add at least one button and color further extend the program choosebutton py by adding some further graphical object shape to the pictureand extend the list shapepairsso they can all be interactively colored (optionalif you would like to carry this furtheralso add prompt to change the outline color of each shapeand then carry out the changes the user desires (optional challenge*look at the pattern within the list buttonsetup it has consistent coordinateand there is regular pattern to the change in the coordinate ( consistent decrease each timethe only data that is arbitrary each time is the sequence of colors write further version choosebutton py with function makebuttonsetupthat takes list of color names as parameter and uses loop to create the list used as buttonsetup end by returning this list use the function to initialize buttonsetup if you likemake the function more general and include parameters for the coordinatethe starting coordinate and the regular coordinate change while statements simple while loops other than the trick with using return statement inside of for loopall of the loops so far have gone all the way through specified list in any case the for loop has required the use of specific list this is often too restrictive python while loop behaves quite similarly to common english usage if say while your tea is too hotadd chip of ice presumably you would test your tea if it were too hotyou would add little ice if you test again and it is still too hotyou would add ice again as long as you tested and found it was true that your tea was too hotyou would go back and add more ice python has similar syntaxwhile condition indentedblock setting up the english example in similar format would bewhile your tea is too hot add chip of ice to make things concrete and numericalsuppose the followingthe tea starts at degrees fahrenheit you want it at degrees chip of ice turns out to lower the temperature one degree each time you test the temperature each timeand also print out the temperature before reducing the temperature in python you could write and run the code belowsaved in example program cool py temperature while temperature first while loop code print(temperaturetemperature temperature print('the tea is cool enough ' while statements |
10,457 | added final line after the while loop to remind you that execution follows sequentially after loop completes if you play computer and follow the path of executionyou could generate the following table rememberthat each time you reach the end of the indented block after the while headingexecution returns to the while heading for another testline temperature comment is truedo loop prints is loop back is truedo loop prints is loop back is truedo loop prints is loop back is falseskip loop prints that the tea is cool each time the end of the indented loop body is reachedexecution returns to the while loop heading for another test when the test is finally falseexecution jumps past the indented body of the while loop to the next sequential statement while loop generally follows the pattern of the successive modification loop introduced with for-each loopsinitialization while continuationcondition do main action to be repeated prepare variables for the next time through the loop test yourselffollowing the code figure out what is printed while print(ii + check yourself by running the example program testwhile py notein pythonwhile is not used quite like in english in english you could mean to stop as soon as the condition you want to test becomes false in python the test is only made when execution for the loop starts (or starts again)not in the middle of the loop predict what will happen with this slight variation on the previous exampleswitching the order in the loop body follow it carefullyone step at time variation on testwhile py while ( ) + print(icheck yourself by running the example program testwhile py the sequence order is important the variable is increased before it is printedso the first number printed is another common error is to assume that will not be printedsince is past but the test that may stop the loop is not made in the middle of the loop once the body of the loop is startedit continues to the endeven when becomes more on flow of control |
10,458 | line comment is truedo loop + = print is truedo loop + print is truedo loop + = no test here print is falseskip loop predict what happens in this related little programnums list( while ( )nums append(ii + print(numscheck yourself by running the example program testwhile py the most general range function there is actually much simpler way to generate the previous sequences like in testwhile pyusing further variation of the range function enter these lines separately in the shell as in the simpler applications of rangethe values are only generated one at timeas needed to see the entire sequence at onceconvert the sequence to list before printingnums range( print(list(nums)the third parameter for the range function is the step size it is needed when the step size from one element to the next is not the most general syntax is rangestart pastend step the value of the second parameter is always past the final element of the list each element after the first in the list is step more than the previous one predict and try in the shelllist(range( )actually the range function is even more sophisticated than indicated by the while loop above the step size can be negative try in the shelllist(range( - )do you see how is past the end of the listtry itmake up range function call to generate the list of temperatures printed in the tea example test it in the shell these rangeslike the simpler ranges that we used earlierare most often used as the sequence in for loop heading while statements |
10,459 | for in range( - )print(iprint('blastoff!'countdown interactive while loops the earlier examples of while loops were chosen for their simplicity obviously they could have been rewritten with range function calls now lets try more interesting example suppose you want to let user enter sequence of lines of textand want to remember each line in list this could easily be done with simple repeat loop if you knew the number of lines to enter for examplein readlines pythe user is prompted for the exact number of lines to be enteredlines list( int(input('how many lines do you want to enter')for in range( )line input('next line'lines append(lineprint('your lines were:'for line in linesprint(linecheck now the user may want to enter bunch of lines and not count them all ahead of time this means the number of repetitions would not be known ahead of time while loop is appropriate here there is still the question of how to test whether the user wants to continue an obvious but verbose way to do this is to ask before every line if the user wants to continueas shown below and in the example file readlines py read it and then run itlines list(testanswer input('press if you want to enter more lines'while testanswer =' 'line input('next line'lines append(linetestanswer input('press if you want to enter more lines'print('your lines were:'for line in linesprint(linesee the two statements setting testanswerone before the while loop and one at the bottom of the loop body notethe data must be initialized before the loopin order for the first test of the while condition to work also the test must work when you loop back from the end of the loop body this means the data for the test must also be set up second timein the loop body (commonly as the action in the last line of the loopit is easy to forget the second timethe readlines py code worksbut it may be more annoying than counting aheadtwo lines must be entered for every one you actually wanta practical alternative is to use sentinela piece of data that would not make sense in the regular sequenceand which is used to indicate the end of the input you could agree to use the line doneeven simplerif you assume all the real lines of data will actually have some text on themuse an empty line as sentinel (if you think about itthe python shell uses this approach when you enter statement with an indented body this way you only need to enter one extra (very simplelineno matter how many lines of real data you have what should the while condition be nowsince the sentinel is an empty lineyou might think line =''but that is the termination conditionnot the continuation conditionyou need the opposite condition to negate condition in pythonyou may use notlike in english more on flow of control |
10,460 | not line ='of course in this situation there is shorter wayline !'run the example program readlines pyshown belowlines list(print('enter lines of text 'print('enter an empty line to quit 'line input('next line'initalize before the loop while line !''while not the termination condition lines append(lineline input('next line'!reset value at end of loopprint('your lines were:'for line in linesprint(lineagain the data for the test in the while loop heading must be initialized before the first time the while statement is executed and the test data must also be made ready inside the loop for the test after the body has executed hence you see the statements setting the variable line both before the loop and at the end of the loop body it is easy to forget the second place inside the loopafter reading the rest of this paragraphcomment the last line of the loop outand run it againit will never stopthe variable line will forever have the initial value you gave ityou actually can stop the program by entering ctrl- that means hold the ctrl key and press noteas you finish coding while loopit is good practice to always double-checkdid make change to the variablesinside the loopthat will eventually make the loop condition falsethe earliest while loop examples had numerical tests and the code to get ready for the next loop just incremented numerical variable by fixed amount those were simple examples but while loops are much more generalin the interactive loop we have seen continuation condition with string testand getting ready 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 just because they have wider variety of continuation condition tests and ways to prepare for the next time through the loop what is consistent is the general steps to think of and questions to ask yourself they keep on applyingkeep these in mindthe need to see whether there is kind of repetitioneven without fixed collection of values to work through to think from the specific situation and figure out the continuation condition that makes sense for your loop to think what specific processing or results you want each time through the loopusing the same code to figure out what supporting code you need to make you ready for the next time through the loophow to make the same results code have new data values to process each time throughand eventually reach stopping point detecting the need for while statementslike with planning programs needing''for'or if statementsyou want to be able to translate english descriptions of problems that would naturally include while statements what are some words or phrases or ideas that suggest the use of these statementsthink of your own and then compare to few gave "while ___""do ___ while""repeat while""repeat until""as long as ___do""keep doing ___ as long as while statements |
10,461 | interactive sum exercise write program sumall py that prompts the user to enter numbersone per lineending with line containing only and keep running sum of the numbers only print out the sum after all the numbers are entered (at least in your final versiondo not create listeach time you read in numberyou can immediately use it for your sumand then be done with the number just entered safe number input exercise there is an issue with reading in numbers with the input statement if you make typo and enter something that cannot be converted from string to the right kind of numbera naive program will bomb this is avoidable if you test 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 whole numberan integer or decimal number all parts refer to the previous is number string exercise (page part refers to the introduction in the previous exercise parts and refer to functions in the solutionisnumberstr pyof the previous exercise make sure you look back at these first save the example safenumberinputstub py as safenumberinput pyand complete it it contains headings and documentation strings for the functions in each part of this exercise this part considers the simplest casewhere you are trying to enter whole number complete the definition of the function safewholenumber complete the function safeint this easily parallels part if you copy in and use the function (not methodisintegerstr complete the function safedecimal this easily parallels part if you copy in and use the function isdecimalstr savings exercise the idea here is to see how many years it will take bank account to grow to at least given valueassuming fixed annual interest write program savings py prompt the user for three numbersan initial balancethe annual percentage for interest as decimallike for %and the final balance desired all the monetary amounts that you print should be rounded to exactly two decimal places start by printing the initial balance this way for exampleif the initial balance was entered as it should be reprinted by your program as also print the balance each year until the desired amount is reached or passed the first balance at or past the target should be the last one printed the maththe amount next year is the amount now times ( interest fraction)so if have $ now and the interest rate is have $ *( $ after one year and after two years have$ *( $ for exampleif respond to the promptsand enter into the program $ starting balance interest rate and target of $ the program prints strange sequence exercise recall strange function exercise (page and its jumpfunc py which contains the function jumpfor any integer njump(nis // if is evenand * + if is odd more on flow of control |
10,462 | you can start with one numbersay and keep applying the jump function to the last number givenand see how the numbers jump aroundjump( * + jump( // jump( * + jump( // jump( // jump( // jump( // this process of repeatedly applying the same function to the most recent result is called function iteration in this case you see that iterating the jump functionstarting from = eventually reaches the value it is an open research question whether iterating the jump function from an integer will eventually reach for every starting integer greater than researchers have only found examples of where it is true stillno general argument has been made to apply to the infinite number of possible starting integers in this exercise you iterate the jump function for specific starting values nuntil the result is save example jumpseqstub py as jumpseq py and complete the missing function bodies if you coded the function jump before in jumpfunc pyyou can copy it you can complete either printjumps or listjumps firstand test before completing the other hint after you have finished and saved jumpseq py copy it and save the file as jumpseqlengths py first modify the main method so it prompts the user for value of nand then prints just the length of the iterative sequence from listjumps(nhint then elaborate the program so it prompts the user for two integersa lowest starting value of and highest starting value of for all integers in the range from the lowest start through the highest startincluding the highestprint sentence giving the starting value of and the length of the list from listjumps(nan example runenter lowest start enter highest start starting from jump sequence length starting from jump sequence length starting from jump sequence length starting from jump sequence length graphical applications another place where while loop could be useful is in interactive graphics suppose you want the user to be able to create polygon by clicking on vertices they choose interactivelybut you do not want them to have to count the number of vertices ahead of time while loop is suggested for such repetitive process as with entering lines of text interactivelythere is the question of how to indicate that you are done (or how to indicate to continueif you make only certain region be allowed for the polygonthen the sentinel can be mouse click outside the region the earlier interactive color choice example already has method to check if mouse click is inside rectangleso that method can be copied and reused creating polygon is unified activity with clear resultso let' define function it involves boundary rectangle and mouse clicks in graphwinand may as well return the polygon constructed read the following startdef polyhere(rectwin)''draw polygon interactively in rectangle rectin graphwin win collect mouse clicks inside rect into the vertices of polygon you will need loop you can print/append almost all the numbers in the loop you are likely to omit one number with just this codebut after looking at what you produceit is easy to separately include the remaining number there are several ways to do this recall the built-in len functionit applies to lists while statements |
10,463 | and always draw the polygon created so far when click goes outside rectstop and return the final polygon the polygon ends up drawn the method draws and undraws rect ''it is useful to start by thinking of the objects neededand give them names polygon is needed call it poly list of vertices is needed call it vertices need to append to this list it must be initialized first the latest mouse click point is needed call it pt certainly the overall process will be repetitiouschoosing point after point still it may not be at all clear how to make an effective python loop in challenging situations like this it is often useful to imagine concrete situation with limited number of stepsso each step can be written in sequence without worrying about loop for instance to get up to triangle ( vertices in our list and fourth mouse click for the sentinel)you might imagine the following sequenceundrawing each old polygon before the next is displayed with the latest mouse click includedrect setoutline('red'rect draw(winvertices list(pt win getmouse(vertices append(ptpoly polygon(verticespoly draw(winwith one point pt win getmouse(poly undraw(missing latest point vertices append(ptpoly polygon(verticespoly draw(winwith two points pt win getmouse(poly undraw(missing latest point vertices append(ptpoly polygon(verticespoly draw(winwith three points pt win getmouse(assume outside the region rect undraw(return poly there is fine point here that missed the first time the vertices of an existing polygon do not get mutated in this system new polygon gets created each time with the new vertex list the old polygon does not go away automaticallyand extraneous lines appear in the picture if the old polygon is not explicitly undrawn each time before new version is redrawn with an extra vertex the last polygon you draw should be visible at the endso in the example above where was assuming the third click was the last for the trianglei did not undraw the polygon the timing for each undraw needs to be after the next mouse click and presumably before the revised polygon is createdso it could be before or after the line vertices append(pti arbitrarily chose for it to go before the vertices list is changed the rest of the order of the lines is pretty well fixed by the basic logic if you think of the repetitions through large number of loopsthe process is essentially circular (as suggested by the word 'loop'the body of loop in pythonhoweveris written as linear sequenceone with first line and last linea beginning and an end we can cut circular loop anywhere to get piece with beginning and an end in practicethe place you cut the loop for python has one main constraintthe processing in python from the end of one time through the loop to the beginning of the next loop is separated by the test of the condition in the heading the continuation condition in the while heading must make sense where you cut the loop it can help to look at concrete example sequencelike the steps listed above for creating triangleonly now assuming more on flow of control |
10,464 | we do not know how many vertices will be chosen the continuation condition is for pt to be in the rectangleso using the previously written function isinsidethe loop heading will be while isinside(ptrect)with this condition in mindlook for where to split to loop it needs to be after new pt is clicked (so it can be testedand before the next polygon is created (so it does not include the sentinel point by mistakein particularwith the sequence abovelook and see that the split could go before or after the poly undraw(line exercise moving undraw (page considers the case where the split goes before this line will proceed with the choice of splitting into python loop after the undraw line this makes the loop be while isinside(ptrect)vertices append(ptpoly polygon(verticespoly draw(winpt win getmouse(poly undraw(if you follow the total sequence of required steps above for making the concrete triangleyou see that this full sequence for the loop is only repeated twice the last time there is no poly undraw(step could redo the loop moving the undraw line to the topwhich caused different issues (exercise moving undraw (page belowinstead think how to make it work at the end of the final time through the loop there are several possible approaches you want the undraw line every time except for the last time hence it is statement you want sometimes and not 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 loopand you have just read the next value for ptyou could just add condition in front of the last line of the loopif isinside(ptrect)poly undraw( find this option unaestheticit means duplicating the continuation test twice in every loop instead of avoiding the undraw as you exit the loopanother option in this case is to undo itjust redraw the polygon one final time beyond the loop this only needs to be done oncenot repeatedly in the loop then the repetitious lines collapse neatly into the loop if you look at the overall concrete sequence for the trianglenot all the lines are in the loop you must carefully include the lines both that come before the loop and those that come after the loop make sure these lines are not put in the loopbut before or afteras indicated by the concrete sequence in the example in the end the entire function isdef polyhere(rectwin)''draw polygon interactively in rectangle rectin graphwin win collect mouse clicks inside rect into the vertices of polygonand always draw the polygon created so far when click goes outside rectstop and return the final polygon the polygon ends up drawn the method draws and undraws rect ''rect setoutline("red"rect draw(winvertices list(pt win getmouse(while isinside(ptrect)vertices append(ptpoly polygon(verticespoly draw(winpt win getmouse(poly undraw(poly draw(win while statements |
10,465 | rect undraw(return poly make sure you understandfollow this code throughimagining three mouse clicks inside rect and then one click outside of rect compare the steps to the ones in the concrete sequence written out above and see that the match (aside from the last canceling undraw and draw of polythis function is illustrated in the example program makepoly py other than standard graphics example codethe main program containsrect rectangle(point( )point( )poly polyhere(rect winpoly setfill('green'rect rectangle(point( )point( )poly polyhere(rect winpoly setoutline('orange'as you can seethe returned polygons are used to make color changesjust as an illustration in earlier animation examples while loop would also have been useful rather than continuing the animation fixed number of timesit would be nice for the user to indicate by 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 work in an animationbecause the computer stops and waits for click with getmouse()whereas the animation should continue until the click in full-fledged graphical systems that respond to eventsthis is no problem zelle' graphics is built on top of capable event-driven systemand in factall mouse clicks are registeredeven outside calls to getmouse(as an examplerun example program randomcircleswhile py be sure to follow the prompt saying to click to start and to end aside from the promptsthe difference from the previous randomcircles py program is the replacement of the original simple repeat loop heading for in range( )by the following initialization and while loop headingwhile win checkmouse(=none#newthe graphics module remembers the last mouse clickwhether or not it occurred during call to getmouse( way to check if the mouse has been clicked since the last call to getmouse(is checkmouse(it does not wait for the mouse as in getmouse(instead it returns the remembered mouse click the most recent mouse click in the pastunless there has been no mouse click since the last call to getmouse or checkmouse in that case checkmouse(returns none (the special object used to indicate the lack of regular objectthe checkmouse method allows for loop that does not stop while waiting for mouse clickbut goes on until the heading test detects that the mouse was clicked similar elaboration can be made for the other examples of animationlike bounce py in bouncewhile py modified bounce py to have while loop in place of the for-loop repeating times run it the only slight added modification here was that win was not originally parameter to bounceinboxso included it look at the source code for bouncewhile pywith the few changes marked new in bounce py also made more interesting change to the initializationso the initial direction and speed of the mouse are determined graphically by the userwith mouse click try example program bounce py the program includes new utility function to help determine the initial (dxdyfor the animation this is done by calculating the move necessary to go from one point (where the ball is in this programto another (specified by user' mouse click in this program more on flow of control |
10,466 | def getshift(point point )new utility function '''returns tuple (dxdywhich is the shift from point to point ''dx point getx(point getx(dy point gety(point gety(return (dxdysince the function calculates both change in and yit returns tuple straightforward interactive methodgetusershiftis wrapped around this function to get the user' choicewhich ultimately returns the same tupledef getusershift(pointpromptwin)#new direction selection '''return the change in position from the point to mouse click in win first display the prompt string under point ''text text(point(point getx() )prompttext draw(winuserpt win getmouse(text undraw(return getshift(pointuserptin the new version of the main driverbounceballexcerpted belowthis interactive setting of (dxdyis used note the multiple assignment statement to both dx and dyset from the tuple returned from getusershift this shift would generally be much too much for single animation stepso the actual values passed to bounceball are scaled way down by factor scale center point(win getwidth()/ win getheight()/ #new central starting point ball makedisk(centerradiuswin#new interactive direction and speed setting prompt ''click to indicate the direction and speed of the ballthe further you click from the ballthe faster it starts ''(dxdygetusershift(centerpromptwinscale to reduce the size of animation steps bounceinbox(balldx*scaledy*scalexlowxhighylowyhighwinthe bounceinbox method has the same change to the loop as in the randomcircles py example the method then requires the graphwinwinas further parametersince checkmouse is graphwin method you can look in idle at the full source code for bounce py if you like the changes from bounce py are all marked with comment starting with #newand all the major changes have been described above in the examples so far of the use of checkmouse()we have only used the fact that point was clickednot which point the next example versionbounce pydoes use the location of mouse clicks that are read with checkmouse(to change the direction and speed of the ball try it this version only slightly modifies the central animation functionbounceinboxbut wraps it in another looping function that makes the direction and speed of the ball change on each mouse click hence the mouse clicks detected in bounceinbox need to be remembered and then returned after the main animation loop finishes that requires nameptto be given to the last mouse clickso it can be remembered this means modifying the main animation loop to initialize the variable pt before the loop and reset it at the end of the loopmuch as in the use of getmouse(for the interactive polygon creation that explains the first three new lines and the last two new lines in the revised bounceinboxdef bounceinbox(shapedxdyxlowxhighylowyhighwin)''animate shape moving in jumps (dxdy)bouncing when while statements |
10,467 | its center reaches the low and high and coordinates the animation stops when the mouse is clickedand the last mouse click is returned ''delay pt none #new while pt =none#new shape move(dxdycenter shape getcenter( center getx( center gety(isinside true #new if xhighdx -dx isinside false #new if yhighdy -dy isinside false #new time sleep(delayif isinsidenew don' mess with dxdy when outside pt win checkmouse(#new return pt #new def moveinbox(shapestopheightxlowxhighylowyhighwin)#new '''shape bounces in win so its center stays within the low and high and coordinatesand changes direction based on mouse clicksterminating when there is click above stopheight ''scale pt shape getcenter(starts motionless while pt gety(stopheight(dxdygetshift(shape getcenter()ptpt bounceinbox(shapedx*scaledy*scalexlowxhighylowyhighwindef makedisk(centerradiuswin)'''return red disk that is drawn in win with given center and radius ''disk circle(centerradiusdisk setoutline("red"disk setfill("red"disk draw(winreturn disk def getshift(point point )'''returns tuple (dxdywhich is the shift from point to point ''dx point getx(point getx(dy point gety(point gety(return (dxdydef bounceball()'''make ball bounce around the screenand react to mouse clicks ''win graphwin('ball bounce ' win yup(#new to mark and label the area where click stops the program lineheight win getheight( textheight win getheight( more on flow of control |
10,468 | line(point( lineheight)point(win getwidth()lineheight)draw(winprompt 'click above the line to stop\nor below to move toward the click text(point(win getwidth()/ textheight)promptdraw(winradius xlow radius center is separated from the wall by the radius at bounce xhigh win getwidth(radius ylow radius yhigh lineheight radius #new lower top to bouncing limits center point(win getwidth()/ lineheight/ ball makedisk(centerradiuswinmoveinbox(balllineheightxlowxhighylowyhighwin#new win close(bounceball( initially made only the changes discussed so far (not the ones involving the new variable isinsidethe variable isinside was in response to bug that will discuss after introducing the simple function that wraps around bounceinboxeach time the mouse is clickedthe ball is to switch direction and move toward the last clickuntil the stopping condition occurswhen there is click above the stop line this is clearly repetitive and needs while loop the condition is simply to test the coordinate of the mouse click against the the height of the stop line the body of the loop is very shortsince we already have the utility function getshiftto figure out (dxdyvalues def moveinbox(shapestopheightxlowxhighylowyhighwin)#new '''shape bounces in win so its center stays within the low and high and coordinatesand changes direction based on mouse clicksterminating when there is click above stopheight ''scale pt shape getcenter(starts motionless while pt gety(stopheight(dxdygetshift(shape getcenter()ptpt bounceinbox(shapedx*scaledy*scalexlowxhighylowyhighwinthe variable pt for the last mouse click needed to be initialized some way chose to make the value be the same as the initial position of the ballso both dx and dy are initially and the ball does not start in motion (alternatives are in random start exercise (page below occasionally detected bug when using the program the ball would get stuck just outside the boundary and stay there the fact that it was slightly beyond the boundary was cluefor simplicity had cheatedand allowed the ball to go just one animation step beyond the intended boundary with the speed and small step size this works visually the original code was sure to make an opposite jump back inside at the next step after some thoughti noticed that the initial version of the bounce py code for bounceinbox broke that assumption when the ball was where bounce-back is requireda mouse click could change (dxdyand mess up the bounce the idea for fix is not to let the user change the direction in the moment when the ball needs to bounce back neither of the original boundary-checking if statementsby itselfalways determines if the ball is in the region where it needs to reverse direction dealt with this situation by introducing boolean variable isinside it is initially set as trueand then either of the if statements can correct it to false thenat the end of the loopisinside is used to make sure the ball is safely inside the proper region when there is check for new mouse click and possible user adjustment to (dxdy while statements |
10,469 | exercise moving undraw *as discussed above at where to split the loop (page )the basic loop logic works whether the poly undraw(call is at the beginning or end of the loop write variation makepoly py that makes the code work the other waywith the poly undraw(at the beginning of the loop do not change or move any other statement in the loop the new place to cut the loop does affect the code before and after the loop in particularthe extra statement drawing poly is not needed after the loop is completed make other changes to the surrounding code to make this work hints make path exercise *write program that is outwardly very similar to makepoly pyand call it makepath pywith function pathhere the only outward difference between polyhere and pathhere is that while the first creates closed polygonand returns itand the new one creates polygonal pathwithout the final point being automatically connected to the first pointand list of the lines in the path is returned internally the functions are quite different the change simplifies some thingsno need to undraw anything in the main loop just draw the latest segment each time going from the previous point to the just clicked point there are complications howeveryou do need deal specially with the first point it has no previous point to connect to suggest you handle this before the main loopif the point is inside the rectangledraw the point so it is visible guide for the next point before returningundraw this initial point (the place on the screen will still be visible if an initial segment is drawn if no more points were addedthe screen is left blankwhich is the way it should beand an empty list of lines should be returned you also need to remember the previous point each time through the main loop suggest you think individually about what should happen if you stop the drawing when the firstsecond or third point is outside the rectangle also test each of those cases after the program is written in your main programcall the makepath function two times use the list of lines returned to loop through and change the color of all the lines in one path and the width of the lines in the other path portion of sample image from this program is shown below the basic issue is similar to the old versionthe undraw is not always needed at the beginning in this case in this place it is not needed the first time through the loop the two basic approaches considered for the previous version still work heremake an extra compensating action outside the loop or break into cases inside the loop further hintit is legal to draw polygon with an empty vertex list nothing appears on the screen more on flow of control |
10,470 | random start exercise (optionali chose to have the ball start motionlessby making the initial value of pt (which determines the initial (dxdybe the center of the ball write variation startrandom py so pt is randomly chosen also make the initial location of the ball be random you can copy the function getrandompoint from bounce py mad lib while exercise *write program madlib py that modifies the getkeys method of madlib py to use while loop (this is not an animation programbut this section is where you have had the most experience with while loops!hintsthis is actually the most natural approach avoided while loops initiallywhen only for loops had been discussed in the original approachhoweverit is redundant to find every instance of '{to count the number of repetitions and then find them all again when extracting the cue keys more natural way to control the loop is while loop stopping when there are no further occurrences of '{to find this involves some further adjustments you must cut the loop in different place (to end after searching for '{'as discussed beforecutting loop in different place may require changes before and after the looptoo find hole game exercise *write graphical game programfindhole py"find the holethe program should use random number generator to determine circular "hole"selecting point and perhaps the radius around that point these determine the target and are not revealed to the player initially the user is then prompted to click around on the screen to "find the hidden holeyou should show the points the user has tried once the user selects point that is within the chosen radius of the mystery pointthe mystery circle should appear there should be message announcing how many steps it tookand the game should end hintyou have already seen the code to determine the displacement (dxdybetween two pointsuse the getshift function in bounce py once you have the displacement (dxdybetween the hidden center and the latest mouse clickthe distance between the points is (dx*dx dy*dy)** using the pythagorean theorem of geometry if this distance is no more than the radius that you have chosen for the mystery circlethen the user has found the circleyou can use getshift as writtenor modify it into function getdistance that directly returns the distance between two points many elaborations on this game are possiblehave fun with itfancier animation loop logic (optionalthe final variation is the example program bounce pywhich has the same outward behavior as bounce pybut it illustrates different internal design decision the bounce py version has two levels of while loop in two methodsmoveinbox for mouse clicks and bounceinbox for bouncing the bounce py version puts all the code for changing direction inside the main animation loop in the old outer functionmoveinbox there are now three reasons to adjust (dxdy)bouncing off the sidesbouncing off the top or bottomor mouse click that is simplification and unification of the logic in one sense the complication now is that the logic for determining when to quit is buried deep inside the if-else logicnot at the heading of the loop the test for mouse clicks is inside the while loop and further inside another if statement the test of the mouse click may merely lead to change in (dxdy)or is signal to quit here is the revised codewith discussion afterward of the return statementdef moveinbox(shapestopheightxlowxhighylowyhighwin)''animate shape moving toward any mouse click below stopheight and bouncing when its center reaches the low or high or coordinates the animation stops when the mouse is clicked at stopheight or above ''scale while statements |
10,471 | delay dx #new dx and dy are no longer parameters dy #new while true#new exit loop at return statement center shape getcenter( center getx( center gety(isinside true if xhighdx -dx isinside false if yhighdy -dy isinside false if isinsidept win checkmouse(if pt !none#new dealing with mouse click now here if pt gety(stopheightswitch direction (dxdygetshift(centerpt(dxdy(dx*scaledy*scaleelse#new exit from depths of the loop return #new shape move(dxdytime sleep(delayrecall that return statement immediately terminates function execution in this case the function returns no valuebut bare return is legal to force the exit since the testing is not done in the normal while conditionthe while condition is set as permanently true this is not the most common while loop patternit obscures the loop exit the choice between the approach of bounce py and bounce py is matter of taste in the given situation arbitrary types treated as boolean the following section would merely be an advanced topicexcept for the fact that many common mistakes have their meaning changed and obscured by the boolean syntax discussed you have seen how many kinds of objects can be converted to other types any object can be converted to boolean (type boolread the examples shown in this shell sequencebool( true bool(- true bool( false bool( false bool(nonefalse bool(''false bool(' 'true bool('false'true bool([]false more on flow of control |
10,472 | bool([ ]true the result looks pretty strangebut there is fairly short general explanationalmost everything is converted to true the only values among built-in types that are interpreted as false are the boolean value false itself any numerical value equal to ( but not or - the special value none any empty sequence or collectionincluding the empty string (''but not ' or 'hior 'false'and the including empty list ([]but not [ , or [ ] possibly useful consequence occurs in the fairly common situation where something needs to be done with list only if it is nonempty in this case the explicit syntaxif len(alist dosomethingwith(alistcan be written with the more succinct pythonic idiom if alistdosomethingwith(alistthis automatic conversion can also lead to extra troublesuppose you prompt the user for the answer to yes/no questionand want to accept 'yor 'yesas indicating true you might write the following incorrect code read itans input('is this ok'if ans ='yor 'yes'print('yesit is ok'the problem is that there are two binary operations here==or comparison operations all have higher precedence than the logical operations orandand not the if condition above can be rewritten equivalently with parentheses read and consider(ans =' 'or 'yesother programming languages have the advantage of stopping with an error at such an expressionsince string like 'yesis not of type bool pythonhoweveraccepts the expressionand treats 'yesas true to testrun the example program boolconfusion pyshown belowans 'yif ans ='yor 'yes'print(' is ok'ans 'noif ans ='yor 'yes'print('no is ok!!???'python detects no error the or expression is treated as truesince 'yesis non-empty sequenceinterpreted as true the intention of someone writing if ans ='yor 'yes'presumably was that the condition meant something like (ans =' 'or (ans ='yes' arbitrary types treated as boolean |
10,473 | this version also translates directly to other languages another correct pythonic alternative that groups the alternate values together is ans in [' ''yes'which reads pretty much like english be careful to use correct expression when you want to specify condition like this things get even strangerenter these conditions themselvesone at timedirectly into the shell' ='yor 'yes'no='yor 'yes' ='yand 'yes'no='yand 'yes'noor 'yes'noand 'yesthe meaning of ( or band of ( and bare exactly as discussed so far if each of the operands and are actually booleanbut more elaborate definitions are needed if an operand is not booleanval or means if bool( )val elseval and in similar veinval and means if bool( )val elseval this strange syntax was included in python to allow code like in the following example program ornotboolean py read and test if you likedefaultcolor 'redusercolor input('enter coloror just press enter for the default'color usercolor or defaultcolor print('the color is'colorwhich sets color to the value of defaultcolor if the user enters an empty string againthis may be useful to experienced programmersbhe syntax can certainly cause difficult bugsparticularly for beginnersthe not operator always produces result of type bool further topics to consider gives an application of python to the web it does not introduce new language features we have come to end of the new language features in this tutorialbut there are certainly more basic topics to learn about programming and python in particularif you continue in other places more on flow of control |
10,474 | creating your own kinds of objects (writing classes inheritancebuilding new classes derived from existing classes python list indexing and slicingboth to read and change parts of lists other syntax used with loopsbreakcontinueand else exception handling python' variable length parameter listsand other options in parameter lists list comprehensionsa concisereadablefast pythonic way to make new lists from old ones event handling in graphical programming listingmoving and deleting stored filescreating folders recursion (not special to python) powerful programming technique where functions call themselves beyond these language featurespython has vast collection of useful modules for examplei wrote real-world programsakaihw pythat have in regular use for processing large numbers of files submitted to sakai in homework submissions it uses string methods and slicing and both kinds of loopsas well is illustrating some useful components in modules sysosand os pathfor accessing command line parameterslisting file directoriescreating foldersand moving and renaming files summary comparison operators produce boolean result (type booleither true or false)[more conditional expressions (page )meaning less than greater than less than or equal greater than or equal equals not equal math symbol <>python symbols <>=!comparisons may be chained as in < ! (page )[multiple tests and if-elif statements the in operator[arbitrary types treated as boolean (page )value in sequence is true if value is one of the elements in the sequence operators on boolean expressions [compound boolean expressions (page )(acondition and condition true only if both conditions are true (bcondition or condition true only if at least one condition is true (cnot condition true only when condition is false this description is sufficient if the result is used as boolean value (in an if or while conditionsee arbitrary types treated as boolean (page for the advanced use when operands are not explicitly booleanand the result is not going to be interpreted as boolean summary |
10,475 | if statements (asimple if statement [simple if statements (page )if condition indentedstatementblockfortruecondition if the condition is truethen do the indented statement block if the condition is not truethen skip it (bif-else statement [if-else statements (page )if condition indentedstatementblockfortruecondition elseindentedstatementblockforfalsecondition if the condition is truethen do the first indented block only if the condition is not truethen skip the first indented block and do the one after the else(cthe most general syntax for an if statementif-elif-else [multiple tests and if-elif statements (page )if condition indentedstatementblockfortruecondition elif condition indentedstatementblockforfirsttruecondition elif condition indentedstatementblockforfirsttruecondition elif condition indentedstatementblockforfirsttruecondition elseindentedstatementblockforeachconditionfalse the ifeach elifand the final else line are all aligned there can be any number of elif lineseach followed by an indented block (three happen to be illustrated above with this construction exactly one of the indented blocks is executed it is the one corresponding to the first true conditionorif all conditions are falseit is the block after the final else line (dif-elif [multiple tests and if-elif statements (page )the elseclause above may also be omitted in that caseif none of the conditions is trueno indented block is executed while statements [simple while loops (page )while condition indentedstatementblock more on flow of control |
10,476 | do the indented block if condition is trueand at the end of the indented block loop back and test the condition againand continue repeating the indented block as long as the condition is true after completing the indented block execution does not stop in the middle of the blockeven if the condition becomes false at that point while loop can be used to set up an (intentionallyapparently infinite loop by making condition be just true to end the loop in that casethere can be test inside the loop that sometime becomes trueallowing the execution of return statement to break out of the loop [fancier animation loop logic (optional(page ) range function with three parameters [simple while loops (page )rangestart pastend step return list of elements start start step with each element step from the previous oneending just before reaching pastend if step is positivepastend is larger than the last element if step is negativepastend is smaller than the last element type tuple expression expression and so on expression (aa literal tuplewith two or more elementsconsists of comma separated collection of values all enclosed in parentheses literal tuple with only single element must have comma after the element to distinguish from regular parenthesized expression [loops and tuples (page )(ba tuple is kind of sequence (ctuplesunlike listsare immutable (may not be altered interpretation as boolean (truefalse)all python data may be converted to boolean (type boolthe only built-in data that have boolean meaning of falsein addition to false itselfare nonenumeric values equal to and empty collections or sequenceslike the empty list {[]}and the empty string '[arbitrary types treated as boolean (page ) additional programming techniques (athese techniques extend the techniques listed in the summary of the previous (page )[summary (bthe basic pattern for programming with while loop is [simple while loops (page )initialization while continuationcondition main action to repeat prepare variables for next time through loop (cinteractive while loops generally follow the pattern [interactive while loops (page )input first data from user while continationconditionbasedontestofuserdata summary |
10,477 | process user data input next user data often the code to input the first data and the later data is the samebut it must appear in both places(dsentinel loops [interactive while loops (page )often the end of the repetition of data-reading loop is indicated by sentinel in the dataa data value known to both the user and the program to not be regular datathat is specifically used to signal the end of the data (enesting control flow statements [nesting control-flow statements (page ) if statements may be nested inside loopsso the loop does not have to execute all the same code each timeit just needs to start with the same test ii loops may be nested the inner loop completes its repetitions each time before going back to the outer loop heading (fbreaking repeating pattern into loop [graphical applications (page )since loop is basically circularthere may be several choices of where to split it to list it in the loop body the split point needs to be where the continuation test is ready to be runbut that may still allow flexibility when you choose to change the starting point of the loopand rotate statements between the beginning and the end of the loopyou change what statements need to be included before and after the loopsometimes repeating or undoing actions taken in the loop (gtuples in lists [loops and tuples (page ) list may contain tuples for-each loop may process tuples in listand the for loop heading can do multiple assignments to variables for each element of the next tuple (htuples as return values [loops and tuples (page ) function may return more than one value by wrapping them in tuple the function may then be used in multiple assignment statement to extract each of the returned variables graphics (azelle' graphics graphwin method checkmouse(allows mouse tests without stopping animationby testing the last mouse clicknot waiting for new one [graphical applications (page )(bthe most finished examples of using zelle' graphics are in [loops and tuples (page )and [graphical applications (page ) more on flow of control |
10,478 | four dynamic web pages overview this leads up to the creation of dynamic web pages these pages and supporting programs have you using simple python web server available on your local machine if you have accessthe pages and programs may be uploaded to public server accessible to anyone on the internet few disclaimersthis tutorial does not cover uploading to an account on public server no core python syntax is introduced in this only few methods in couple of python library modules are introduced the is by no means major source of information about specific html codes the appendix html source markup (page introduces the limited source code for the html markup needed for the dynamic web exercisesand bit more beyond that you can avoid dealing with specific codes with the use of modern wordprocessor-like html editor as specific examplethe open source html editor kompozer is discussedplus little bit about the mac application texteditsince kompozer is not available for osx versions from catalina on you need to work in folder where all the folders above itup to the root folder for your hard drivehave no blanks in the name as long as your home folder has no blank in the namethe folder can be under thatlike on your desktop or in your documents if you do have blank in the name of your home folderyou will need to keep the files for this elsewhere that may mean separate folder on yur hard drive or on removable drive like flash drive if the examples subfolder www is not in place with all further up folders having no blank in the namesthen move it now the does allow you to understand the overall interaction between browser (like firefox on your local machineand web server and to create dynamic web content with python we treat interaction with the web basically as mechanism to get input into python program and data back out and displayed web pages displayed in your browser are used for both the input and the output the advantage of public server is that it can also be used to store data accessible to people all over the world there are number of steps in the development in this so start with an overview few bits about the basic format of hypertext markup language are useful to start the simplest static pages can be written with word-processor or by modifying simple html source examples next we look at pages generated dynamically an easy way to accomplish this is to create specialized static pages to act as templates into which the dynamic data is easily embedded web page creation can be tested totally locallyby creating html files and pointing your web browser to them initially we supply input data by |
10,479 | our traditional means (keyboard input or function parameters)and concentrate on having our python program convert the input to the desired html outputand display this output in web page we generate data from within web pageusing web forms initially we will test web forms by automatically dumping their raw data to fully integrate browser and serverwe (ause web forms to provide data(buse python program specified on the servercalled cgi scriptto access the web form data and transform the input data into the desired output(cembed the output in new dynamic web page that gets sent back to your browser this python server program transforms the input dataand generates output web pages much like we did in step above web page basics format of web page markup documents can be presented in many forms simple editor like idle or windowsnotepad produce plain textessentially long string of meaningful characters that appear in the final text you view documents can be displayed with formatting of parts of the document web pages allow different fontsitalicand boldfaced emphasesand different sized text and paragraph layouts microsoft wordlibre officeand osx pagesall display documents with various amounts of formatting the syntax for the ways different systems encode the formatting information varies enormously if you look at an old microsoft word doc document in plain text editor like notepadyou should be able to find the original text buried insidebut most of the symbols associated with the formatting are unprintable gibberish as far as human is concerned hypertext markup language (htmlis very different in that regard it produces file of entirely human-readable charactersthat could be produced with plain text editorbut the markup parts of the file do not appear directly in your browserbut instruct the browser how to format the page for instance in htmlthe largest size of heading with the text "web introduction"would look like web introduction the heading format is indicated by bracketing the heading text 'web introductionwith markup sequencesbeforehandand afterward all html markup is delimited by tags enclosed in angle bracketsand most tags come in pairssurrounding the information to be formatted the end tag has an extra '/here 'hstands for headingand the number indicates the relative importance of the heading (there is also for smaller headings in the early days of htmlediting was done in plain text editorwith the tags being directly typed in by people who memorized all the codeswe will use little enough of the markup that the very limited introduction in html source markup (page )along with samples that show easily modified exampleswill cover all the markup you need for the course with the enormous explosion of the world wide webspecialized software has been developed to make web editing be much like word processingwith graphical interfaceallowing formatting to be done by selecting text with mouse and clicking menus and icons labeled in more natural language the software then automatically generates the necessary markup in this tutoriala possible example for windows users and macs that are not upgraded to the catalina osx versionis the freeopen source kompozer from users of catalinaor later osx versionscan look at the introduction to the mac app textedit in html source markup (page dynamic web pages |
10,480 | if your operating system fitsyou might download kompozerif you are not already using another environment that lets you see both the unformatted plain text and the formatted view an alternative for the simple markup needed for exercises is to modify example html source code using the ideas in html source markup (page introduction to static pages in kompozer if you cannot run kompozeryou can see the parallel html source discussion in html source markup (page )and skip this section that is specifically on kompozer this section introduces the kompozer web page editor to create static pages static page is one that is created ahead of time and just opened and used as needed this is as opposed to dynamic pagewhich is custom page generated by software on demandgiven some input parameters you can open kompozer and easily generate document with headingand italic and boldfaced portions kompozer is used because it is free softwareand is pretty easy to uselike common word processor unlike common word processor you will be able to easily look at the html markup code underneath it is not necessary to know lot about the details of the markup codes for html files to use kompozerbut you can see the results of the markup we will use static pages later as part of making dynamic pagesusing the static pages as templates in which we insert data dynamically to creating static web pages however you start kompozergo to the menu in kompozer and select file new you will get what looks like an empty document look at the bottom of your window you should see normal tab selectedwith other choices beside itincluding source tab click on the source tab you should see thatthough you have added no contentyou already have the basic markup to start an html page click again on the normal tab to go back to the normal view (of no content at the moment assume you are making home page for yourself make title and some introductory text use regular word processor features like marking your title as heading in the drop down box on menu bar (the drop down menu may start off displaying 'paragraphor 'body textyou can select text and make it bold or italicsenlarge it using the editing menu or icons before getting too carried awaysave your document as home html in the existing www directory under your earlier python examples it will save lot of trouble if you keep your web work together in this www directorywhere have already placed number of files that you will want to keep together in one directory just for comparisonswitch back and forth between the normal and source views to see all that has gone on underneath your viewparticularly if you edited the format of your text somewhere embedded in the source view you should see all the text you entered some individual characters have special symbols in html that start with an ampersand and end with semicolon againit is more important the understand that there are two different views than to be able to reproduce the source view from memory you can use your web browser to see how your file looks outside the editor the easiest way to do this is to go to the web browser' menu and select something like file open fileand find the home html file that you just wrote it should look pretty similar to the way it looked in kompozerbut if you had put in hyperlinksthey should now be active the discussion of web page editing continues in editing html forms (page )but first we get python into the act web page basics |
10,481 | editing and testing different document formats notein this you will be working with several different types of documents that you will edit and test in very different ways the ending of their names indicate their use each time new type of file is discussed in later sectionsthe proper ways to work with it will be repeatedbut with all the variationsit is useful to group them all in one place nowweb py my convention for regular python programs taking all their input from the keyboardand producing output displayed on web page these programs can be run like other python programsdirectly from an operating system folder or from inside idle they are not final productbut are way of breaking the development process into steps in testable way cgi python program to be started from web browser and run by web server you will develop code using local web server on your own machine html web documents most often composed in an editor like kompozer by my conventionthese have subcategories template html not intended to be displayed directly in browserbut instead are read by python program cgi or web pyto create template or format string for final web page that is dynamically generated inside the python program other files ending in html are intended to be directly viewed in web browser except for the simple static earlier examples in introduction to static pages in kompozer (page )the pages for this course are designed to reside on web serverand include forms that can pass information to python cgi program cgito make this work on your computer have all the web pages in the same directory as the example program localcgiserver py it is easiest to leave it in the www subdirectory of your examples directory looking ahead to when we get to using server dynamically (cgi dynamic web pages (page ))(ainclude the python cgi server programs in the same directory (bhave localcgiserver py runningstarted from directory windownot from inside idle (cin the browser url fieldthe web page file name must be preceded by for examplethe running localcgiserver py the url may either by an html file or possibly cgi file for examplelocalcgiserver py(dmost often cgi programs are referenced in web formand the program is called indirectly by the web server cgi programs can be edited and saved inside idlebut they do not run properly from inside idle they must be run via the server/browser combination more on this later composing web pages in python dynamically created static local pages from python for the rest of this the example files will come from the www directory under the main examples directory you unzipped will refer to example file there as "example www filesas the overview indicateddynamic web applications typically involve getting input from web page formprocessing the input in program on the serverand displaying output to web page introducing all these new ideas at once dynamic web pages |
10,482 | could be lot to absorbso this section uses familiar keyboard input into regular python program and thenlike in the final versionprocesses the input and produces the final web page output follow this sequence of steps open the example www file hello html in your browserto see what it looks like change your browser view for instance go back to the previous page you displayed open the same hello html file in kompozerif that works for youor another editor that will show the html sourceas discussed in html source markup (page if using kompozerswitch to the source view (clicking the source tabsometimes you will want to copy html text into python program for instancei selected and copied the entire contents of the hello html source view and pasted it into multi-line string in the python program shown and discussed below carefulnote the change from past practice herestart python from inside the www directory in windows you may start idle with the idleonwindows shortcut that placed in the www directorynot the original example directory open the www example program helloweb py in an idle edit window run it you should see familiar web page appear in your default browser (possibly not the one you have been usingthis is obviously not very necessary programsince you can select this page directly in your browserstillone step at timeit illustrates several useful points the program is copied below read it''' simple program to create an html file froma given stringand call the default web browser to display the file ''contents ''<meta content="text/htmlcharset=iso- - http-equiv="content-type"hello helloworld''def main()browselocal(contentsdef strtofile(textfilename)"""write file with the given name and the given text ""output open(filename," "output write(textoutput close(def browselocal(webpagetextfilename='tempbrowselocal html')'''start your webbrowser on local file containing the text with given filename ''import webbrowseros path strtofile(webpagetextfilenamewebbrowser open("file:///os path abspath(filename)#elaborated for mac main( composing web pages in python |
10,483 | this program encapsulates two basic operations into the last two functions that will be used over and over the firststrtofilehas nothing newit just puts specified text in file with specified name the secondbrowselocaldoes more it takes specified text (presumably web page)puts it in fileand directly displays the file in your default web browser it uses the open function from the webbrowser module to start the new page in your web browser the open function here requires the name of file or url since the page is automatically generated by the program for one-time immediate viewingit automatically uses the same throwaway filenametempbrowselocal html specified as the default in the keyword parameter if you really want another specificname you could pass it as parameter in this particular program the text that goes in the file is just copied from the literal string named contents in the program this is no advance over just opening the file in the browser directlystillit is start towards the aim of creating web content dynamically an early example in this tutorial displayed the fixed hello world!to the screen this was later modified in hello_you py to incorporate user input using the string format method of dictionaries and string formatting (page )person input('enter your name'greeting 'hello {person}!format(**locals()print(greetingsimilarlyi can turn the web page contents into format stringand insert user data load and run the www example program helloweb py the simple changes from helloweb py are marked at the beginning of the file and shown below modified the web page text to contain 'hello{person}!in place of 'helloworld!'making the string into format stringwhich renamed to the more appropriate pagetemplate the changed initial portion with the literal string and and the main program then becomes pagetemplate ''<meta content="text/htmlcharset=iso- - http-equiv="content-type"hello hello{person}''new note '{person}two lines up def main()new person input("enter name"contents pagetemplate format(**locals()browselocal(contentsnow the line contents pagetemplate format(**locals()incorporaties the person' name into the contents for the web page before saving it to file and displaying it in this casei stored the literal format string inside the python programbut consider different approachload and run the www example program helloweb py it behaves exactly like helloweb pybut is slightly different internally it does not directly contain the web page template string instead the web page template string is read from the file hellotemplate html dynamic web pages |
10,484 | below is the beginning of helloweb pyshowing the only new functions the firstfiletostrwill be standard function used in the future it is the inverse of strtofile the main program obtains the input in this simple examplethe input is used directlywith little further processing it is inserted into the web pageusing the file hellotemplate html as format string def filetostr(filename)new """return string containing the contents of the named file ""fin open(filename)contents fin read()fin close(return contents def main()person input('enter name'contents filetostr('hellotemplate html'format(**locals()browselocal(contentsnew although hellotemplate html is not intended to be viewed by the user (being template)you should open it in browser or web editor (kompozer or to look at it it is legal to create web page in web page editor with expressions in braces embedded in itif you look in the source view in kompozer or in web source editoryou will see something similar to the literal string in helloweb pyexcept the lines are broken up differently (this makes no difference in the formatted resultsince in htmlall white space is considered the same back in the normal mode in kompozeror in source mode for any html editoradd an extra line of text right after the line "hello{person}!then save the file again (under the same namerun the program helloweb py againand see that you have been able to change the appearance of the output without changing the python program itself that is the aim of using the template html pageallowing the web output formatting to be managed mostly independently from the python program more complicated but much more common situation is where the input data is processed and transformed into results somehowand these resultsoften along with some of the original inputare embedded in the output web page that is produced as simple exampleload and run the www example program additionweb pywhich uses the template file additiontemplate html the aim in the end of this is to have user input come from form on the web rather than the keyboard on local machinebut in either case the input is still transformed into results and all embedded in web page to make parts easily reusablei obtain the input in distinct place from where the input is processed in keeping with the later situation with web formsall input is of string type (using keyboard input for nowlook at the program you will see only few new linesbecause of the modular designmost of the program is composed of recent standard functions reused the only new code is at the beginning and is shown heredef processinput(numstr numstr )new '''process input parameters and return the final page as string ''num int(numstr transform input to output data num int(numstr total num +num return filetostr('additiontemplate html'format(**locals()def main()new numstr input('enter an integer'obtain input numstr input('enter another integer'contents processinput(numstr numstr process input into page browselocal(contentsdisplay page composing web pages in python |
10,485 | the input is obtained (via input for now)and it is processed into web page stringand as separate step it is displayed in local web page there are few things to noteall input is strings before the numerical calculationsthe digit strings must be converted to integers do calculate ( very simple!result and use it in the output web page although it is not in the python codean important part of the result comes from the web page format string in additiontemplate htmlwhich includes the needed variable names in braces{num }{num }and {totalview it in your browser or in web editor when you write your own codeyou might modify additionweb pyor you can start from stripped down skeleton in the example www folderskeletonforweb pywith comments about where to insert your special code we will examine the bottom part of the following diagram later the top part outlines the flow of data from string input to web page in your browser for regular python program like what we have been describingwith the processing outlined in the middle line the parts in the middle will be common to the later client/server programthat manges input and output with the bottom linethat we will discuss later againthis last section was somewhat artificial you are not in the end likely to find such programs practical as end products however such programs are reasonable to write and test and they include almost all the code you will need for more practical (but harder to debugcgi programcoming next quotient web exercise save additionweb py or skeletonforweb py as quotientweb py modify it to display the results of division problem in web page as in the exercises in display full sentence labeling the initial data and both the integer quotient and the remainder you can take your calculations from quotient string return exercise (page you should only need to make python changes to the processinput and main functions you will also need the html for the output page displayed make web page template file called quotienttemplate html and read it into your program turn in both quotientweb py and quotienttemplate html cgi dynamic web pages cgi stands for common gateway interface this interface is used by web servers to process information requests supplied by browser python has modules to allow programs to do this work the convention used by many servers is to have the server programs that satisfy this interface end in cgithat is the convention used below all files below ending in cgiare cgi programs on web serverand in this they will all be python programs (though there are many other languages in use for this purposethese programs are often called scriptsso we will be dealing with python cgi scripts you cannot run cgi file from inside idle dynamic web pages |
10,486 | an example in operation the web examples folder provides simple web serverbuilt into pythonthat you can run on your own computer (it is also possible to set your computer up with the right software to be server for the internet that is totally unnecessary for this class windows in an operating system file windowgo to the folder with the www examples depending on the setup of your operating systemthere are several ways to start the local server that might work double click on startserver cmdwhich have placed in the example www folder if this does not worktry right click on localcgiserver py in the file explorer windowand select open with -python launcher if neither workcheck if you need to modify your python installationcovered in some special windows instructions (page )and then try the startserver cmd approach again mac this is more involved the first time see some special mac instructions (page you should see console window pop upsaying "localhost cgi server startedthis approach starts the localcgiserver py server without monopolizing idle once the server is startedleave the server console window there as long as you want the local server running for that folder warningdo not start the local server running from inside idle it will monopolize idle noteif the server aborts and gives an error message about spaces in the pathlook at the path through the parent directories over this www directory if any of the directory names have spaces in themthe local file server will not work in case of this erroreither go up the directory chain and alter the directory names to eliminate spaces or move the examples directory to directory that does not have this issue for very simple but complete example make sure you have the local server going open the web link you see web form follow the instructionsenter integersand click on the find sum button you get back web page that obviously used your data look at the local server console window you should see log of the activity with the server we will end up completely explaining the web pages and cgi file needed to accomplish thisallowing you to generalize the ideabut for now just see how it works first consider the rather involved basic execution steps behind the scene the data you type is handled directly by the browser it recognizes forms an action instruction is stored in the form saying what to do when you press button indicating you are ready to process the data (the find sum button in this case in the cases we consider in this tutorialthe action is given as web resourcegiving the location of cgi script on some server (in our casesthe same directory on the server as the current web pageit is resource handled by the local serverwhen the url starts with "file all the url' you use for this section and its exercises should start that way when you press the buttonthe browser sends the data that you entered to that web location (in this case adder cgiin the same folder as the original web page cgi dynamic web pages |
10,487 | the server recognizes the web resource as an executable scriptsees that it is python programand executes it with the python interpreterusing the data sent along from the browser form as input the script runsmanipulates its input data into some resultsand puts those results into the text of web page that is the output of the program via print statements the server captures this output from the program and sends it back to your browser as new page to display you see the results in your browser close the server window test what happens if you try to reload the web link you refer to localhostbut you just stopped the local server for the rest of this we will be wanting to use the local serverso restart it in the example www folderin manner appropriate for your operating systemwindowswhatever worked when you started it the first time macstart the local server whatever way worked last timeeither double clicking on cgiserverscript that you should have createdor right/control click on localcgiserver py in the finder windowand select open with -python launcher now you can keep the local server going as long as you want to run cgi scripts from the same folder if you ever want be have cgi scripts and supporting files in different folderstop the server for any other folder firstand start it up in the folder where you have your materials simple buildup before we get too complicatedconsider the source code of couple of even simpler examples hellotxt cgi the simplest case is cgi script with no input that just generates plain textrather than html assuming you have your local server goingyou can go to the link directoryhellotxt cgiand below for you to read#!/usr/bin/env python required header that tells the browser how to render the text print("content-typetext/plain\ \ "here text -not html print simple message to the display window print("helloworld!\ "the top line is what tells the operating system that this is python program it says where to find the right python interpreter to process the rest of the script this exact location is significant on unix derived server (like any mac with os xin windows the only thing important in the line is the distinction between python and if you leave the line there as part of your standard textyou have one less thing to think about when uploading to unix server or running on mac the first print function is telling the server receiving this output that the format of the rest of the output will be plain text this information gets passed back to the browser later this line should be included exactly as stated if you only want the output to be plain text (the simplest casebut not our usual casethe rest of the output (in this case just from one print functionbecomes the body of the plain text document you see on your browser screenverbatim since it is plain text the server captures this output and redirects it to your browser dynamic web pages |
10,488 | hellohtml cgi we can make some variation and display an already determined html page rather than plain text try the link you to read#!/usr/bin/env python print("content-typetext/html\ \ "html markup follows print(""hello in html hello therehi there"""there are two noteworthy changes the first print function call now declares the rest of the output will be html this is standard boilerplate line you will be using for your cgi programs the remaining print function call has the markup for an html page note that the enclosing triple quotes work for multi line string other than as simple illustrationthis cgi script has no utilityjust putting the contents of the last print function in file for static web page hello html would be much simpler now cgi one more simple stepwe can have cgi script that generates dynamic output by reading the clock from inside of pythontry the link from static page the code is in the www example directorynow cgiand below for you to read#!/usr/bin/env python import time print("content-typetext/html\ \ "html markup follows timestr time strftime("% "obtains current time htmlformat ""the time now the current central date and time is""print(htmlformat format(**locals()){timestrsee {timestrembedded above this illustrates couple more ideasfirst library moduletimeis imported and used to generate the string for the current date and time the web page is generated like in helloweb pyembedding the dynamic data (in this case the timeinto literal web page format string (note the embedded {timestrunlike helloweb pythis is cgi script so the web page contents are delivered to the server just with print function cgi dynamic web pages |
10,489 | adder cgi it is small further step to get to processing dynamic input try filling out and submitting the adder form one more timedisplayed you should see something like the following (only the numbers should be the ones you entered)this shows one mechanism to deliver data from web form to the cgi script that processes it the names and are used in the form (as we will see laterand the data you entered is associated with those names in fact form is not needed at all to create such an associationif you directly go to the urls or you get arithmetic displayed without the form this is just new input mechanism into the cgi script you have already seen program to produce this adder page from inside regular python program taking input from the keyboard the new cgi versionadder cgionly needs to make few modifications to accept input this way from the browser new features are commented in the source and discussed below the new parts are the import statement through the main functionand the code after the end of the filetostr function read at least these new parts in the source code shown below#!/usr/bin/env python import cgi new def main()new except for the call to processinput form cgi fieldstorage(standard cgi script lines to hereuse format of next two lines with your names and default data numstr form getfirst(" "" "get the form value associated with form name 'xuse default " if there is none numstr form getfirst(" "" "similarly for name 'ycontents processinput(numstr numstr process input into page print(contentsdef processinput(numstr numstr )'''process input parameters and return the final page as string ''num int(numstr transform input to output data num int(numstr total num +num return filetostr('additiontemplate html'format(**locals()standard code for future cgi scripts from here on def filetostr(filename)"""return string containing the contents of the named file ""fin open(filename)contents fin read()fin close(return contents new print("content-typetext/html\ \ "main(exceptcgi print_exception(try say generating html catch and print errors dynamic web pages |
10,490 | first the overall structure of the codeto handle the cgi input we import the cgi module the main body of the code is in main methodfollowing good programming practice after the definition of main come supporting functionseach one copied from the earlier local web page versionadditionweb py at the end is the newboilerplate cgi wrapper code for main(this is code that you can always just copy chose to put the initial print function herethat tells the server html is being produced that mean the main method only needs to construct and print the actual html code also keep the final try-except block that catches any execution errors in the program and generates possibly helpful trace information that you can see from your browser (how to write such error catching code in general is not covered in this introductory tutorialbut you can copy it in this situation!the main function has three sectionsas in the local web page versionread input (this time from the formnot the keyboard)process itand generate the html output reading inputthe first line of main is standard one (for you to copythat sets up an object called form that holds the cgi form data accompanying the web request sent by the browser you access the form data with statements like the next two that have the patternvariable form getfirstnameattrib default if there is form input field with name nameattribits value from the browser data is assigned to variable if no value is given in the browser' data for nameattribvariable is set equal to default instead in this way data associated with names given by the browser can be transferred to your python cgi programand if there is no such name in form feeding this cgi programthe program does not immediately bomb out in this program the values associated with the browser-supplied names'xand ' 'are extracted use slightly verbose python variable names that remind you that all values from the browser forms are strings the processinput function that is passed the input parameters from whatever sourceis exactly the same as in additionweb pyso we already know it worksoutput the page in cgi scriptthis is easier than with the local web pagesjust print it no need to save and separately display filethe server captures the "printedoutput this program can now serve as template for your own cgi scriptsthe only things you need to change are the lines in main(that get the input from web formusing the names from the input tags in the formand assigning the string values to python varibles in main call processinputwith all the data from the form that you need to pass as parameters to processinput the heading of the definition of processinput need to fit with the actual parameters passed by the call in main(furthermore the processinput part can be written and tested earlier with python program in the format of the web py programs that we have discussed while this is the only python codeyou still need to create an output web page templateand refer to it as the parameter of filetostr againif you tested your logic using an earlier web py programjust use the same output web templatea stripped down skeletonto start cgi program fromwith comments about needed changes is in skeletonfor cgi if you do not want to start your code by modifying an existing example cgi programthen you might start by copying skeletonfor cgi idle and cgi files you can always start idle way that you have beforelike on an existing py file then deal with editing cgi files from inside idle cgi dynamic web pages |
10,491 | for macsee the part of some special mac instructions (page for way to start idle on cgi file easilyafter some initial work the first time on windowsthe easiest thing may be to use idleonwindows cmd you will want to open and save cgi files in idle then dialog windows in both windows and on mac have the same ideasbut different labels there is file type filter field for both it is labeled "formaton mac on windowsfor savingit is labeled "save as type"and for opening filethere is field it at the lower rightunlabeled if you want file ending in cgichange the filter field to all files (*for savingbe sure to enter the full file name you wantwith the extensioncgi if you forget and do not change the file filter when savinga pywill be added to your file name then you can rename it in an operating system file folder in the following diagramnow we have discussed both the top regular python sequence using the topthe bottom cgi specific sequenceand the common part in the middleas shown in both cases input data gets processed into the content of web page that goes to browser for any major application the main work is in the processing in the middle since that part is shared in both approachesit can be tested with simple python programbefore the starting and ending steps of the input and output flow are changed for the cgi client/server model the only part that still needs details explained is for web forms before going on to thatit is time to talk about handling errors in the cgi scripts we have been discussing the programs discussed here follow the simple patternget all input dataprocess input dataoutput results all together this pattern can be used both in testing web py version and in dynamic cgi versionusing processinput function common to both clearly more complicated patterns are often needed when inputprocessingand output are mixed in different waybut for these examples and for the exercisesthis is all we need errors in cgi scripts before you start running your own cgi scripts on the local serverit is important to understand how the different kinds of errors that you might make will be handled if you write regular python programeven one that produces web pageyou can write the code and run it in idleand idle will display all the kinds of errors with cgi scriptyou can still use idle to write your codebut you cannot run the cgi code in idleand errors show up in three different placesdepending on their typesyntax errors you are encouraged to check for syntax errors inside idleby using the menu sequence run -check module if you fail to do this and try running script with syntax errorthe error trace appears in the console window that appears when you start the local server better to have it fixed before thenwhile you are still dynamic web pages |
10,492 | editing if you want an illustrationyou might try changing adder cgimaking an error like impor cgiand try using adder html with the flawed script (then fix it and try again if you find it in idleyou can jump to the line where the error was detected execution errors the error trace for execution errors is displayed in your web browserthanks to the final boilerplate code with the try-catch block at the end of the cgi script if you omit that final boilerplate codeyou completely lose descriptive feedbackbe sure to include that boilerplate codeyou can also see an illustration now get an error by introducing the statementbad 'aappend(' 'in the main function and run it (then take it out server errors your work can cause an issue inside the local servernot directly in the python execution some errors are communicated to the browserbut not necessarily all other errors appear in the log generated in the local server' window you could have file named wrongfor instancein any operating system alsoon mac or in linuxwhere the cgi script needs to be set as executablean error with non-executable cgi script only shows up in this log in the local server window you should be able to fix this error by running the cgifix py programin the same folder logical errors since your output appears in the web browserwhen you produced something legal but other than what you intendedyou see it in the browser if it is formatting errorfix your output page template if you get wrong answerscheck your processinput function here is an outline for client/server program testingemphasizing errors to be conscious of and avoid if you have problemsplease actively check out this whole listyou are encouraged to add your files into the examples www folder if you really want to work in different folderyou will want to copy number of support files into that foldercgifix py and localcgiserver,pyplus dumpcgi cgi if you want to test web forms separately for windowsstartserver cmd on mac be sure to run cgifix pyto generate the folder-specific version of cgiserverscript if you want an easy environment to test fancy processinput functionembed it in regular python programas we have discussed for web py programs then you can test it normally in idle this will also allow you to make sure the web templatethat you refer to in your processinput functionis in legitimate formwith substitutions only for local variables you can code cgi script in idlebut not run it be sure to save it with the suffix cginot py do not run it it idle the only testing you can do in idle is for syntaxusing the menu sequence run -check module or its keyboard shortcut do run that test at the end of your cgi scriptmake sure you include the boilerplate code that catches execution errors remember to run cgifix py in the same folder as precaution to clean things upparticularly with new file on mac make sure your local server is goingand that all the files you reference are in the same folder as the local server make sure you test your page by starting it in your web browser with url starting will not cause an obvious error the dynamic actions will just not take place if you are not paying attentionthis can happen and be very confusingif things do not workremember the three places to check for errors after initially checking for syntax errors in idlethe remaining errors might be displayed on the output page in the browser (if you confirmed that you have the try-catch boilerplate code at the endif that does not totally explain thingsremember to check the server console windowtoo we have not covered web forms yetbut rather than bite off too much at oncethis is good time to write your own first cgi script in the following exercise cgi dynamic web pages |
10,493 | quotient cgi exercise modify quotient web exercise (page and save it as cgi script quotient cgi in the same directory where you have localcgiserver py and your output html page template from quotientweb py make quotient cgi take its input from browserrather than the keyboard this means merging all the standard cgi code from adder cgi with the processinput function code from your quotientweb py please keep the same web form data names'xand ' 'as in adder cgiso the main method should not need changes from adder cgi remember to test for syntax errors inside idleand to have the local web server running when you run the cgi script in your browser since we have not yet covered web formstest your cgi script by entering test data into the url in the browser in particular use links the form after trying these linksyou can edit the numbers in the url in the browser to see different results editing html forms this section is continuation of introduction to static pages in kompozer (page )intended for users running kompozer parallel developmentwithout kompozerthat may be simpler is in html source markup (page this section is about html editing using kompozer not about python html forms will allow user-friendly data entry for python cgi scripts this is the last elaboration to allow basic web interactionenter data in formsubmit itand get processed result back from the server the initial exampleadder htmlhad form with only text input fields and submit button inside you will not need anything with further kinds of markup for the exercises now open adder html in kompozer switch to the source view this is short enough page that you should not get lost in the source code the raw text illustrates another feature of htmlattributes the tag to start the form contains not only the tag code formbut also several expressions that look like python assignment statements with string values the names on the left-hand side of the equal signs identify type of attributeand the string value after the equal sign gives the corresponding string value for the attribute the tag for many kinds of input fields is input notice that each field includes name and value attributes (so there is some confusion possible here from the fact the value is the name of particular attributeand all attributes have string as their value will try to use the phrase "string valueconsistently for the second usage see that the 'xand 'ythat are passed in the url by the browser come from the name attribute given in the html code for the corresponding fieldskompozer and other web editors translate your menu selections into the raw html code with proper attribute types this high level editor behavior is convenient to avoid having to learn and debug the exact right html syntaxon the other handusing pop-up field editing windows has the disadvantage that you can only see the attributes of one field at timeand likely need mutiple mouse clicksplus typing particularly if you want to modify number of name or value attributesit is annoying that you need number of mouse clicks to go from one field to the next if you only want to modify the string values assigned to existing attributes like name and valueit may be easier to do in the source windowwhere you can see everything at once (or use separate html source editoras described in html source markup (page making syntax errors in the html source in not very likely if the only changes that you makle to tags are data inside quoted value strings the action url is property of the entire form to edit it in kompozer via the guiright click inside the formbut not on any field elementand select the bottom pop-up choiceform properties then you see window listing the action url and you can change the value to the name of the cgi script that you want to receive the form data when you create your own web formi suggest you make the initial action url be dumpcgi cgi this will allow you to debug your form separate from your cgi script when you have tested that your web form has all the right names and initial valuesyou can change the action url to your cgi script name (like quotient cgi)and go on to test the combination of the form and the cgi scriptif you are modifying previous working formit is likely easier to use the source viewand just replace the value of the form' action attribute to the new cgi file name dynamic web pages |
10,494 | optionallyyou can test various input methods by opening and playing with to allow easy concentration on the data sent by the browserthis form connects to simple cgi script dumpcgi cgithat just dumps and labels all the form data to web page press the submit button in the formand see the result back up from the output to the previous pagethe formand change some of the data in all kinds of fields submit again and see the results play with this until you get the idea clearly that the form is passing on your data if you want to create form and input fields using the kompozer guiopen this same filethe www example commonformfields htmlin kompozer the static text in this page is set up as tutorial on forms in kompozer read the content of the page describing how to edit at least forms with text input fields and submit buttons the other fancier fields are optional not needed for the exercises read the static text about how to edit individual fieldsand change some field parameterssave the file and reload it in your browserand submit again if you change the name or value attributesthey are immediately indicated in the dumped output if you change things like the text field sizeit makes change in the way the form looks and behaves you can return to the original versionan extra copy is saved in commonformfieldsorig html now we have discussed the last pieceweb formsin the diagram for the comparison of generating web pages dynamically by regular python program or server cgi scriptnote the last three python videos do not directly corresponding to single place in the tutorial text instead they go through the entire process for web based programs from the beginning video creates birthday html web form looking forward to birthday cgi of video in the middle video creates birthdayweb pytesting the process function and output template to be used in birthday cgi quotientweb form exercise complete the web presentation for quotient cgi of quotient cgi exercise (page by creating web form quotient html that is intelligible to user and which supplies the necessary data to quotient cgi be sure to test the new form on your local serverusing the url you must have the local server running first you must have all the associated files in the same directory as the server program you are runningand you cannot just click on quotient html in file browser you must start it from the the url dynamic web programming exercise make simple complete dynamic web presentation with cgi script that uses at least three user inputs from form the simplest would be to just add three numbers instead of two call your form dynamic html call your cgi script dynamic cgi call an output template dynamictemplate html remember the details listed in the previous exercise to make the results work on localhost after the server is started and you have all the filesgo to summary (page starts with the overall process for creating dynamic web pages cgi dynamic web pages |
10,495 | more advanced examples this is an optional section one of the advantages of having program running on public server is that data may be stored centrally and augmented and shared by all in high performance sites data is typically stored in sophisticated databasebeyond the scope of this tutorial for less robust but simpler way to store data persistentlywe can use simple text files on the server the www example page namelist html uses namelist cgi to maintain file namelist txt of data submitted by users of the page you can test the program with your local python server it is less impressive when you are the only one who can make changesthe source code is documented for those who would like to have look you also may want to look at the source code of the utility script you have been usingdumpcgi cgi it uses method of getting values from the cgi data that has not been discussedval form getlist(namethis method returns list of values associated with name from the web form the list many have or many elements it is needed if you have number of check boxes with the same name (maybe you want list of all the toppings someone selects for pizza both dumpcgi cgi and namelist html add an extra layer of robustness in reflecting back arbitrary text from user the user' text may include symbols used specially in html like '<the function safeplaintext replaces reserved symbols with appropriate alternatives the examples in earlier sections were designed to illustrate the flow of data from input form to output pagebut neither the html or the data transformations have been very complicated more elaborate situation is ordering pizza onlineand recording the orders for the restaurant owner you can try and look at the supporting example www files pizza cgipizzaordertemplate htmland the simple pizzareporttemplate html to see the reportthe owner needs to know the special name owner after ordering several pizzasenter that name and press the submit button again this cgi script gets used in two ways by regular userinitiallywhen there is no orderand later to confirm an order that has been submitted the two situations use different logicand the script must distinguish what is the current use hidden variable is used to distinguish the two caseswhen pizza cgi is called directly (not from form)there is no paststate field on the other hand the pizzaordertemplate html includes hidden field named paststatewhich is set to the value 'order(you can confirm this by examining the end of the page in kompozer' source mode the cgi script checks the value of the field paststateand varies its behavior based on whether the value is 'orderor not the form in pizzaordertemplate html has radio buttons and check boxes hard coded into it for the optionsand copies of the data are in pizza cgi keeping multiple active copies of data is not good ideathey can get out of sync if you look at the source code for pizzaordertemplate htmlyou see that all the entries for the radio button and check box lines are in similar form in the better version with altered files pizza cgi and pizzaordertemplate html (that appears the same to the user)the basic data for the pizza options is only in one place in pizza cgiand the proper number of lines of radio buttons and check boxes with the right data are generated dynamically to do the dynamic generationtemplates for an individual html line with size radio button is in the source codeand it is used repeatedly to generate multiple lineseach with different size and price embedded into the format string from the program data these lines are joined together and placed as one entity into the html form template similar procedure is done with the toppings and check-boxes the logic of using the hidden input field is futher outlined in html source markup (page further possible elaboration would be to also allow the restaurant manager to edit the sizecost and available topping data onlineand store the data in file rather than having the data hard coded in pizza cgiso if the manager runs out of toppingshe can remove it from the order form this change would be fairly elaborate project compared to the earlier exercises dynamic web pages |
10,496 | summary the overall process for creating dynamic web pages making dynamic web pages has number of steps have suggested several ways of decoupling the partsso you can alter the orderbut if you are starting from nothingyou might follow the following sequence(adetermine the inputs you want to work with and make web form that makes it easy and obvious for the user to provide the data you may initially want to have the form' action url be dumpcgi cgiso you can debug the form separately test with the local server when everything seems okmake sure to change the action url to be the name of the cgi script you are writing [editing html forms (page )(bit is easier to debug regular python program totally inside idle than to mix the idle editor and server execution particularly if the generation of output data is going to be complicated or there are lots of places you are planning to insert data into an output templatei suggest you write the processinput function with its output template first and test it without serveras we did with additionweb pyproviding either canned input in the main programor taking input data from the keyboardand saving the output page to local file that you examine in your webbrowser [dynamically created static local pages from python (page )(cwhen you are confident about your processinput functionput it in program with the proper cgi skeletonand add the necessary lines at the beginning of the main function to take all the cgi script input from the browser data include all the variable names you need in the actual parameter list for calling processinput they should match up with the formal parameters you wrote earlier for the definition of processinput [adder cgi (page )(dbe sure to check for syntax errors in idleby using the menu sequence run -check module fix as necessary (eremember to run cgifix py in the same folder as precaution to clean things upparticularly with new cgi file on mac (ffinally test the whole thing with the local server make sure the local server is runningand all the resources that you refer to are in the same folder as the local web serverinitial web pageweb page templatescgi script do not open the starting web page or cgi script in idle or by finding it in your file system you must run it in your browser with url that starts with load web page directly from your file systemit will not cause an obvious error the dynamic actions will just not take place (gif is does not work rightif you get page that uses your templatebut it looks wrongeither fix your template or look for logical error in your program (if you had tested your processinput function in regular python program beforethis should not happen if the web page output shows an error descriptionsee if you can pick any help out and go back and fix your code if you get nothing back in your web browsermake sure you had tested the final version of the code in idle for syntax errors (run -check module)and that you have the final error catching code in the cgi scriptand that you used url that starts with if all of the parts mentioned above are therethe problem may show in the servernot python look in the local server window' log outputand see if it points to filename that it cannot find or markupplain text may be marked up to include formatting the formatting may be easily interpreted only by computeror it may be more human readable one form of human-readable markup is hypertext markup language (html[format of web page markup (page ) summary |
10,497 | (ahtml markup involves tags enclosed in angle braces computer science ending tags start with '/for instance tags may be modified with attributes specified similar to python string assignmentsfor example the text input field tag(bmodern editors allow html to be edited much like in word processor two views of the data are usefulthe formatted view and the source viewshowing the raw html markup python and htmlsince html is just text stringit can easily be manipulated in pythonand read and written to text files [dynamically created static local pages from python (page ) the webbrowser module has function openthat will open file or web url in your default browser[dynamically created static local pages from python (page )webbrowser openfilename common gateway interface (cgithe sequence of events for generating dynamic web page via cgi[an example in operation (page )(athe data user types is handled directly by the browser it recognizes forms (bthe user presses submit button an action is stored in the form saying what to do when the button is pressed (cin the cases we consider in this tutorialthe action is given as web resourcegiving the location of cgi script on some server the browser sends the data that you entered to that web location (dthe server recognizes the page as an executable scriptsees that it is python programand executes itusing the data sent along from the browser form as input (ethe script runsmanipulates the input data into some resultsand puts those results into the text of web page that is the output of the program (fthe server captures this output from the program and send it back to the user' browser as new page to display (gthe results appear in the user' browser the cgi module (acreate the object to process cgi input with [adder cgi (page )form cgi fieldstorage((bextract the first value specified by the browser with name nameattribor use default if no such value exists [adder cgi (page )variable form getfirstnameattrib default (cextract the list of all values specified by the browser associated with name nameattrib [more advanced examples (page )listvariable form getlistnameattrib this case occurs if you have number of checkboxesall with the same namebut different values the list may be empty local python servers (apython has module for creating local testing server that can handle static web pages and python cgi scripts [an example in operation (page ) dynamic web pages |
10,498 | (bdifferent kinds of errors with cgi scripts are handled different ways by local python server [errors in cgi scripts (page ) comparison of the various types of files used in web programminglisting the different ways to edit and use the filesis given in editing and testing different document formats (page summary |
10,499 | dynamic web pages |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.