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 ... |
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 w... |
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 undern... |
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 constru... |
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 insi... |
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'hea... |
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 wan... |
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 line... |
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 wind... |
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 ... |
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 ... |
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 states... |
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 programm... |
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 t... |
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 w... |
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... |
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 shapeli... |
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 functionbec... |
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... |
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 ... |
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 th... |
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 make... |
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 animatio... |
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 enterin... |
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... |
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 color... |
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 ... |
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 s... |
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... |
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... |
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... |
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 o... |
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 th... |
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 objec... |
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 t... |
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... |
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 b... |
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 a... |
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 ... |
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 alte... |
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 he... |
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... |
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 st... |
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 fun... |
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... |
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 integersnumsretur... |
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(i... |
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 th... |
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 op... |
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'wind... |
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 s... |
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 "the... |
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... |
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... |
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 forever... |
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 w... |
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 add... |
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 he... |
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 actua... |
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... |
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 ... |
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 immediatel... |
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 s... |
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 nee... |
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 teste... |
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 illus... |
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 ... |
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 fals... |
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 ra... |
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 ... |
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 fro... |
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(stoph... |
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 c... |
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... |
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 parame... |
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 el... |
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 tha... |
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 t... |
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 disclaimersthi... |
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... |
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 in... |
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 repeat... |
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 ... |
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... |
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 fi... |
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 ou... |
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 t... |
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 o... |
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 de... |
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 ... |
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 newboilerpl... |
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 dif... |
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 yo... |
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... |
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... |
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 simpl... |
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 t... |
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 ar... |
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.