id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
10,300 | 'xxx{: }yyyformat(' ''xxxayyy'xxx{: }yyy {: 'xxxayyy -substitute string -pad to spaces (left aligns by default the real fun starts when we put something inside those curly brackets these are the formatting instructions the simplest examples start with colon followed by some layout instructions (we will see what comes in front of the colon in few slides time the number indicates how many spaces to allocate for the insertion and the letter that follows tells it what type ob object to expect "sstands for string |
10,301 | 'xxx{:< }yyyformat(' ''xxxayyy'xxx{:< }yyy {:< 'xxxayyy -align to the left (- by default strings align to the left of their space we can be explicit about this by inserting left angle bracketwhich you can think of as an arrow head pointing the direction of the alignment |
10,302 | 'xxx{:> }yyyformat(' ''xxxayyy'xxx{:> }yyy {:> 'xxxayyy -align to the right (- if we want right aligned strings then we have to use the alignment marker |
10,303 | 'xxx{: }yyyformat( 'xxx yyy'xxx{: }yyy {: 'xxx yyy -substitute an integer (digits -pad to spaces (right aligns by default if we change the letter to "dwe are telling the format(method to insert an integer ("digits"these align to the right by default |
10,304 | 'xxx{:> }yyyformat( 'xxx yyy'xxx{:> }yyy 'xxx yyy {:> -align to the right (- we can be explicit about this if we want |
10,305 | 'xxx{:> }yyyformat( 'xxx yyy'xxx{:< }yyy {:< -align to the left (-'xxx yyy and we have to be explicit to override the default |
10,306 | 'xxx{: }yyyformat( 'xxx yyy'xxx{: }yyy {: -pad with zeroes 'xxx yyy if we precede the width number with zero then the number is padded with zeroes rather than spaces and alignment is automatic |
10,307 | 'xxx{:+ }yyyformat( 'xxx+ yyy'xxx{:+ }yyy 'xxx+ yyy {: -always show sign if we put plus sign in front of the number then its sign is always showneven if it is positive |
10,308 | 'xxx{:+ }yyyformat( 'xxx+ yyy'xxx{:+ }yyy {: -always show sign 'xxx+ yyy -pad with zeroes and we can combine these |
10,309 | 'xxx{: , }yyyformat( 'xxx , yyy'xxx{: , }yyy {: , - , 'xxx , yyy adding comma between the width and the "dadds comma breaks to large numbers |
10,310 | 'xxx{: }yyyformat( 'xxx yyy'xxx{: }yyy 'xxx yyy {: ff -substitute float - places in total - places after the point floating point numbers are slightly more complicated the width parameter has two partsseparated by decimal point the first number is the width of the entire number (just as it is for strings and integersthe number after the decimal point is the number of decimal points of precision that should be included in the formatted output |
10,311 | 'xxx{: }yyyformat( 'xxx yyy'xxx{: }yyy {: 'xxx yyy { the default is to have six decimal points of precision and to make the field as wide as it needs to be |
10,312 | ' {: } {: } {: }xformat('abc' 'xabcx equivalent ' { : } { : } { : }xformat('abc' 'xabcx what comes before the colonthis is selection parameter detailing what argument to insert the arguments to format(are given numbers starting at zero we can put these numbers in front of the colon |
10,313 | ' { : } { : } { :dxformat('abc' 'xabcx ' { : } { : } { :dxformat('abc' 'xabcx we can also use them to change the order that items appear in or to have them appear more than once (or not at all |
10,314 | formatting '{: {: }for (wordnumberin itemsprint(formatting format(word,number)python counter py cat mat on sat the the script counter py is the same as counter py but with the new formatting for its output |
10,315 | contents |
10,316 | one beginning with python (creleased under the creative commons attribution-noncommercial-share alike united states license context you have probably used computers to do all sorts of useful and interesting things in each applicationthe computer responds in different ways to your inputfrom the keyboardmouse or file still the underlying operations are determined by the design of the program you are given in this set of tutorials you will learn to write your own computer programsso you can give the computer instructions to react in the way you want low-level and high-level computer operations first let us place python programming in the context of the computer hardware at the most fundamental level in the computer there are instructions built into the hardware these are very simple instructionspeculiar to the hardware of your particular type of computer the instructions are designed to be simple for the hardware to executenot for humans to follow the earliest programming was done with such instructions if was difficult and error-prone major advance was the development of higher-level languages and translators for them higher-level languages allow computer programmers to write instructions in format that is easier for humans to understand for example + is an instruction in many high-level languages that means something like access the value stored at location labeled calculate the sum of this value and the value stored at location labeled store the result in location labeled no computer understands the high-level instruction directlyit is not in machine language special program must first translate instructions like this one into machine language this one high-level instruction might be translated into sequence of three machine language instructions corresponding to the three step description above obviously high-level languages were great advance in clarityif you follow broad introduction to computingyou will learn more about the layers that connect low-level digital computer circuits to high-level languages |
10,317 | why python there are many high-level languages the language you will be learning is python python is one of the easiest languages to learn and usewhile at the same time being very powerfulit is one of the most used languages by highly productive professional programmers also python is free languageif you have your own computeryou can download it from the internet obtaining python for your computer even if you have python on your own computeryou may well not have the latest version if you think you already have current python set to gothen try starting idlestarting idle (page if idle startssee if the version stated near the top of its window matches the latest version of pythonthen fineotherwiseif you are using windows or macsee the appendices (page for instructions for individual operating systems linux an older version of python is generally installedand even if current version +is installedidle is not always installed look for package to installsomething like 'idle-python(the name in the ubuntu distributionphilosophy and implementation of the hands-on python tutorials although python is high-level languageit is not english or some other natural human language the python translator does not understand "add the numbers two and threepython is formal language with its own specific rules and formatswhich these tutorials will introduce graduallyat pace intended for beginner these tutorials are also appropriate for beginners because they gradually introduce fundamental logical programming skills learning these skills will allow you to much more easily program in other languages besides python some of the skills you will learn are breaking down problems into manageable parts building up creative solutions making sure the solutions are clear for humans making sure the solutions also work correctly on the computer guiding principals for the hands-on python tutorialsthe best way to learn is by active participation information is principally introduced in small quantitieswhere your active participationexperiencing pythonis assumed in many place you will only be able to see what python does by doing it yourself (in hands-on fashionthe tutorial will often not show among the most common and important words in the tutorial are "try this:other requests are for more creative responses sometimes there are hintswhich end up as hyperlinks in the web page versionand footnote references in the pdf version both formats should encourage you to think actively about your response first before looking up the hint the tutorials also provide labeled exercisesfor further practicewithout immediate answers provided the exercises are labeled at three levels no label immediate reinforcement of basic ideas preferably do on your first pass important and more substantial be sure you can end up doing these allow time to do them*most creative information is introduced in an order that gives you what you need as soon as possible the information is presented in context complexity and intricacy that is not immediately needed is delayed until laterwhen you are more experienced beginning with python |
10,318 | in many places there are complications that are important in the beginningbecause there is common error caused by slight misuse of the current topic if such common error is likely to make no sense and slow you downmore information is given to allow you to head off or easily react to such an error although this approach is an effective way to introduce materialit is not so good for reference referencing is addressed in several waysdetailed table of contents extensive index in the web page version flexible search engine built into the html version (does not work on an html version that you download to your computercross references to sections that elaborate on an introductory section hyperlinks allow you to jump between the referenced parts in the html version or the pdf version viewed on computer the pdf version also gives page references concise summariesgrouping logically related itemseven if that does not match the order of introduction using the tutorial text and video the hands-on python tutorial was originally document to readwith both the html version and pdf version even if you do not print itsome people use the pdf version onlinepreferring its formatting to the formatting in the html version some people learn better visually and verbally from the very beginning the tutorial has videos for many sections also mentioned for the convenience of my comp class are videos beyondpythonfor the part of the class after python the videos are copied into two placesonedrive (ak yqmbq? = there are five zip files of videos that you can download and unzipplus individual mp ' for the python tutorial appendix sections there is one zip file for each - of the python tutorial and one zip file (beyondpython zipfor the remainder of my comp class after the python downloads of the parts do not need any id unzip (expandany zip file before using google driveyou need google drive/docs login id if you are not already logged into google drive/docsyou will need to do it when you click on the link if you have that idthen the advantage of google drive is that you can select exactly what parts to view or download this may not work with internet explorerbut it does work with firefoxsafari or chrome browser to get the most out of the tutoriali strongly suggest the following approach for each partwatch video if you like they are clearly labeled by numerical section stop the video where ask you to think the videos hit the high points and take advantage of being able to point at specific places on the screen they are not as recent as the current textso they may look bit different than the tutorial in web page some details may only appear in the written text stop the video frequently to test things for yourselfif new function is introduceddo not only watch the videobut try it out for yourselfincluding with data not in the video in some places the written version mentions more examples to try context |
10,319 | whether you look at the video of section or notdo look through written versioneither as first pass or to review and fill in holes from the videos be sure to stop and try things yourselfand see how they actually work on your computer look at the labeled exercises you are strongly recommended to give the unstarred ones an immediate try to reinforce basic concepts the starred ones (*are important for strong understanding do not get too far ahead in reading/watching before trying the starred exercises understanding earlier parts well enough to be able to solve problems is going to either be completely necessary for understanding some later sections or at least make later sections easier to follow and fully comprehend python provides too rich an environment to be able to show you all interrelationships immediately that can mean errors send you in strange (to youdirection see the appenidix section using error messages (page have fun and be creativeand discover your power with pythonlearning to problem-solve while the tutorial introduces all the topicsthere is more to say about using it effectively there is way too much detail to just absorb all at onceso what are the first things to learnmore important than memorizing details is having an idea of the building blocks available and how they are useful for the most direct exercisesyou might just look back over the most recent section looking for related thingsbut that will not work when you have scores of sections that might have useful partsthe basic idea of the building blocks should be in your head for instancelooking ahead to when you have finished the tutorial through you will want to have these ideas very present in your head to be ready to start on the exercisesyou can use numbers and do arithmetic you can store and retrieve data using variable names and assignment statements python has many useful built-in functions that can affect the system or return results for you to use you can get keyboard input from the user and print things back for the user data comes in different typesand you can convert where it makes sense you can use strings and generate them in many waysliteral stringsconcatenation operator (+)string format method once you have an idea of the appropriate building blocks needed to solve specific problemthen you can worry about more details particularly at the beginningyou are not likely to have all the exact python syntax for the parts of your solution nailed downit is not important to remember it preciselybut it is important to know how to find clear explanation efficientlyknow the location in examples or in the tutorialor use the indexthe search capacitysummariesand/or write things in notes for yourself as for an exam writing short bits down is also useful because the act of writing helps many people absorb what they are writing as your experience increases you will get used to and remember more and more stuffbut there is always the latest idea/syntax to get used toyour notes of what is importantbut still not in immediate recallwill evolve continuously this multi-tiered approach means that what you absorb should not just be an enormous collection of unstructured facts that you plumb through in its entirety to find useful idea you first need to be particularly aware of the major headings of useful featuresand then do what you need to drill down to details as necessary this approach is important in the real-worldaway from python the world is awash with way to much information to memorizebut you must access the information that you need to synthesize and formulate solutions/arguments effectivelyknowing all the building blocks of solution is obviously important many successful holistic thinkers can do this effectively in some domains knowledge of the pieces and their relationships is enough programming requires more than thishoweverit is critical to sort out the exact sequence in which the pieces must logically appear some beginning with python |
10,320 | excellent holistic thinkers have hard time with this sequencingand must pay extra attention when planning code if you are like thisbe patient and be prepared to ask for help where needed what to do after you finish an exercise is importanttoo the natural thing psychologicallyparticularly if you had struggleis to think"whewoutta here!!!!on something that came automatically or flowed smoothlythat is not big deal you will probably get it just as fast the next time if you had hard time and only eventually got to successyou may be doing yourself disservice with "whewoutta here!!!we have already mentioned how not everything is equally importantand some things are more important to keep in your head than others the same idea applies to all the steps in solving possibly long problem some parts were easysome were hardthere may have been several steps if all of that goes into your brain in one continuous stream of stuff that you remember at the same levelthen you are going to leave important nuggets mixed in with an awful lot of unimportant and basically useless information then the information is likely to all fade into oblivionor be next to impossible to cycle through looking for the useful nuggets why do the problem anyway if you are just going to bury important information further down in your brainwhat is importantthe most obvious thing you will need at higher level of recall is what just messed you upwhat you missed until doing this problemafter finishing the actual problemactively follow up and ask yourselfwhat did get in the end that was missing initiallywhat was the connection madedoes this example fit in to some larger idea/abstraction/generalization in way that did not see beforehow am going to look at this so can make similar connection in similar (or maybe only partly similarproblemis there kernel here that can think of as new tool in my bag of tricksyour answers to these questions are the most important things to take away from your recent hard work the extra consideration puts them more in the "prioritypart of your brainso you can really learn from your effort when you need the important ideas nextyou do not need to play through all the details of the stuff you did to solve the earlier problem keep coming back to this section and check up on your processit is really important the python interpreter and idlepart your python folder and python examples first you need to set up location to store your work and the example programs from this tutorial you can put the folder for your python programs most anywhere you like howeverfor it will be important that none of the directories leading down to your python folder contain any blanks in themin particular your home folder the normal place for you to have my examples folder is under your home folderwhich has the same name as your login id if you are just creating login idit will save some hassle in if your login id does not have space in it "andyor "anhor andyharringtonwould be fine for mebut "andy harringtonwould bomb the server in it is possible to do with folder outside your home folderas discussed at the beginning of folder for my examples download and save the python interpreter and idlepart |
10,321 | note that the exampleslike this version of the tutorialare for python there were major changes to python in version making it incompatible with earlier versions if you are using python version for some good reasonyou should continue with the older version of the tutorial go to once you have the examples zip archiveyou need to extract the files make file browser window set to the directory where you put the zip file thenwindows right click on examples zipselect extract all this will create the folder examples end up with file browser window showing the contents of the examples folder this will be your python folder in later discussion mac double click on the zip file and the expanded examples folder appears warningon windowsfiles in zip archive can be viewed while they are still in the zip archive modifying and adding files is not so transparent be sure that you unzip the archive and work from the regular directory that holds the resulting unzipped files you also have the option of downloading an archive containing the web version of the tutorial examples the local file to open in your browser in in the handsonhtml folder you unzipped and the main web page file to open is called index html the pdf version of the tutorial for printing like html version running sample program this section assumes python is already on your computer windows does not come with python (to load python see obtaining python for your computer (page before getting to the individual details of pythonyou will run simple text-based sample program find madlib py in your python folderset up in your python folder and python examples (page notedifferent keyboards label the key for ending line differentlywindows keyboards may use enter while mac keyboards use return the tutorial may intermix instructions to press enter or press return they both are intended to mean the key for ending line options for running the programif you have trouble with the following optionsopening the program in idle is discussed in starting idle (page in windowsyou can display your folder contentsand double click on madlib py to start the program on macyou can control-click on madlib py in the finderselect open withand choose the python launcher for your python version when you are done with the programclose the terminal window in linux you may be able to open terminal windowchange into your python examples directoryand enter the command python madlib py or possibly to distinguish python and beginning with python |
10,322 | python madlib py if neither of these workget help try the program second time and make different responses sample programexplained if you want to get right to the detailed explanations of writing your own pythonyou can skip to the next section starting idle (page if you would like an overview of working programeven if all the explanations do not make total sense yetread on here is the text of the madlib py programfollowed by line-by-line brief explanations do not worry if you not totally understand the explanationstry to get the gist now and the details later the numbers on the right are not part of the program file they are added for reference in the comments below#/usr/bin/env python ''string substitution for mad lib adapted from code by kirby urner '' storyformat '' once upon timedeep in an ancient jungle there lived {animalthis {animal liked 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 however the {animalbecame homesickso the explorer brought it back to the jungle leaving large supply of {food the end '' def tellstory() userpicks dict( addpick('animal'userpicks addpick('food'userpicks addpick('city'userpicks story storyformat format(**userpicks print(story def addpick(cuedictionary) '''prompt for user response using the cue string and place the cue-response pair in the dictionary '' prompt 'enter an example for cue ' response input(prompt dictionary[cueresponse tellstory( input('press enter to end the program ' line by line explanation the python interpreter and idlepart |
10,323 | #/usr/bin/env python this is not technically part of the program it is there to tell the operating system what version of python to choosesince the older python is incompatible with the newer python we will mostly run programs from inside the idle programming environmentwhere this line is not needed to run just by clicking on the program in an operating system windowhoweverthe line is important if your computer also has python ''string substitution for mad lib adapted from code by kirby urner '' - there is multi-line text enclosed in triple quotes quoted text is called string string at the very beginning of program like this is documentation for the file , , , blank lines are included for human readability to separate logical parts the computer ignores the blank lines storyformat ''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 '' the equal sign tells the computer that this is an assignment statement the computer will now associate the value of the expression between the triple quotesa multi-line stringwith the name on the leftstoryformat - these lines contain the body of the string and the ending triple quotes this storyformat string contains some special symbols making it format stringunlike the string in lines - the storyformat string will be used later to provide format into which substitutions are made the parts of the string enclosed in braces are places substitute string will be inserted later the substituted string will come from custom dictionary that will contain the user' definitions of these words the words in the braces{animal}{food}{city}indicate that animalfoodand city are words in dictionary this custom dictionary will be created in the program and contain the user' definitions of these words these user' definitions will be substituted later in the format string where each is currently def tellstory()userpicks dict(addpick('animal'userpicksaddpick('food'userpicksaddpick('city'userpicksstory storyformat format(**userpicksprint(story def is short for definition of function this line is the heading of definitionwhich makes the name tellstory becomes defined as short way to refer to the sequence of statements that start indented on line and continue through line the equal sign tells the computer that this is another assignment statement the computer will now associate the beginning with python |
10,324 | name userpicks with new empty dictionary created by the python code dict( - addpick is the name for function defined by the sequence of instructions on lines - used to add another definition to dictionarybased on the user' input the result of these three lines is to add definitions for each of the three words animalfoodand city to the dictionary called userpicks assign the name story to string formed by substituting into storyformat using definitions from the dictionary userpicksto give the user' customized story this is where all the work becomes visibleprint the story string to the screen def addpick(cuedictionary) '''prompt for user response using the cue string and place the cue-response pair in the dictionary '' prompt 'enter an example for cue ' response input(prompt dictionary[cueresponse this line is the heading of definitionwhich gives the name addpick as short way to refer to the sequence of statements indented on line - the name addpick is followed by two words in parenthesiscue and dictionary these two words are associated with an actual cue word and dictionary given when this definition is invoked in lines - - documentation comment for the addpick definition the plus sign here is used to concatenate parts of the string assigned to the name prompt the current value of cue is placed into the string the right-hand-side of this equal sign causes an interaction with the userto input text from the keyboardthe prompt string is printed to the computer screenand the computer waits for the user to enter line of text that line of text then becomes string inside the program this string is assigned to the name response the left-hand-side of the equal sign is reference to the definition of the cue word in the dictionary the whole line ends up making the definition of the current cue word become the response typed by the user tellstory(input('press enter to end the program ' the definition of tellstory above does not make the computer do anything besides remember what the instruction tellstory means it is only in this linewith the nametellstoryfollowed by parenthesesthat the whole sequence of remembered instructions are actually carried out this line is only here to accommodate running the program in windows by double clicking on its file icon without this linethe story would be displayed and then the program would endand windows would make it immediately disappear from the screenthis line forces the program to continue being displayed until there is another response from the userand meanwhile the user may look at the output from tellstory starting idle the program that translates python instructions and then executes them is the python interpreter this interpreter is embedded in number of larger programs that make it particularly easy to develop python programs such programming environment is idleand it is part of the standard distribution of python it is possible to open the idle app directlystart searchwindowspress the windows key or go to the start menu the python interpreter and idlepart |
10,325 | macopen spotlight (command-spacebarenter idle in the search field select the idle app if you have linuxthe approach depends on the installation in ubuntuyou should find idle in the programming section of the applications menu you are better starting idle from terminalwith the current directory being your python folder you may need special name set up to distinguish idle for versions and for instance idle for version we will discuss later that if you want to edit filesthis is not the best way to start idlesince the associated folder is not the one you wantbut it works for now windows in idle idle has several parts you may choose to displayeach with its own window depending on the configurationidle can start up showing either of two windowsan edit window or python shell window you are likely to first see an edit windowwhose top left corner looks something like in windowsfor more on the edit windowsee the idle editor and execution (page if you see this edit window with its run menu on topgo to the run menu and choose python shell to open python shell window for now then you may close the edit window for now we will just be using the python shell either initiallyor after explicitly opening ityou should now see the python shell windowwith menu like the followingthough the text may be slightly differentin the shell the last line should look like beginning with python |
10,326 | the is the prompttelling you idle is waiting for you to type something continuing on the same line enter + be sure to end with the enter key after the shell respondsyou should see something like + the shell evaluates the line you enteredand prints the result you see python does arithmetic at the end you see further prompt where you can enter your next line the result lineshowing that is produced by the computerdoes not start with when we get to whole programswe will use the idle editor and execution (page whirlwind introduction to types and functions python directly recognizes variety of types of data here are fewnumbers - character strings'hello''the answer islists of objects of any type[ ]['yes''no''maybe' special datum meaning nothingnone python has large collection of built-in functions that operate on different kinds of data to produce all kinds of results to make function do its actionparentheses are required these parentheses surround the parameter or parametersas in function in algebra class the general syntax to execute function is functionname parameters one function is called typeand it returns the type of any object the python shell will evaluate functions in the shell the last line should look like continuing on the same line enter type( always remember to end with the return (or enterkey after the shell respondsyou should see something like type( in the resultint is the way python abbreviates integer the word class is basically synonym for type in python note that the line with the value produced by the shell does not start with and appears at the left margin hence you can distinguish what the computer responds from what you type (after the promptat the end you see further prompt where you can enter your next line for the rest of this sectionat the prompt in the python shellindividually enter each line below that is set off in typewriter font so next enter whirlwind introduction to types and functions |
10,327 | type( note the name in the last result is floatnot real or decimalcoming from the term "floating point"for reasons that will be explained laterin floatsdivisionmixed types (page enter type('hello'in your last result you see another abbreviationstr rather than string enter type([ ]strings and lists are both sequences of parts (characters or elementswe can find the length of that sequence with another function with the abbreviated name len try both of the followingseparatelyin the shelllen([ ]len('abcd'some functions have no parametersso nothing goes between the parentheses for examplesome types serve as no-parameter functions to create simple value of their type try list(you see the way an empty list is displayed functions may also take more than one parameter try max( abovemax is short for maximum some of the names of types serve as conversion functions (where there is an obvious meaning for the conversiontry each of the followingone at timein the shellstr( int(' 'note the presence and absence of quotes an often handy shell featurean earlier shell line may to copied and edited by clicking anywhere in the previously displayed line and then pressing the return (or enterkey for instance you should have entered several lines starting with len click on any onepress returnand edit the line for different test integer arithmetic addition and subtraction we start with the integers and integer arithmeticnot because arithmetic is excitingbut because the symbolism should be mostly familiar of course arithmetic is important in many casesbut python is probably more often used to manipulate text and other sorts of dataas in the sample program in running sample program (page python understands numbers and standard arithmetic for the whole section on integer arithmeticwhere you see set-off line in typewriter fonttype individual lines at the prompt in the python shell press enter after each line to get python to respond beginning with python |
10,328 | python should evaluate and print back the value of each expression of course the first one does not require any calculation it appears that the shell just echoes back what you printed the python shell is an interactive interpreter as you can seeafter you press return (or enter)it is evaluating the expression you typed inand then printing the result automatically this is very handy environment to check out simple python syntax and get instant feedback for more elaborate programs that you want to savewe will switch to an editor window later multiplicationparenthesesand precedence try in the shell you should get your first syntax error the should have become highlightedindicating the location where the python interpreter discovered that it cannot understand youpython does not use for multiplication as you may have done in grade school the can be confused with the use of as variable (more on that laterinstead the symbol for multiplication is an asterisk enter each of the following you may include spaces or not the python interpreter can figure out what you mean either way (the space can make understanding quicker for human reader try in the shell * if you expected the last answer to be think againpython uses the normal precedence of arithmetic operationsmultiplications and divisions are done before addition and subtractionunless there are parentheses try ( + )* ( now try the following in the shellexactly as writtenfollowed by enterwith no closing parenthesis ( look carefully there is no answer given at the left margin of the next line and no prompt to start new expression if you are using idlethe cursor has gone to the next line and has only indented slightly python is waiting for you to finish your expression it is smart enough to know that opening parentheses are always followed by the same number of closing parentheses the cursor is on continuation line type just the matching close-parenthesis and enterand you should finally see the expression evaluated (in some versions of the python interpreterthe interpreter puts at the beginning of continuation linerather than just indenting negation also works try in the shell-( division and remainders if you think about ityou learned several ways to do division eventually you learned how to do division resulting in decimal try in the shell / / integer arithmetic |
10,329 | as you saw in the previous sectionnumbers with decimal points in them are of type float in python they are discussed more in floatsdivisionmixed types (page in early grade school you would likely say " divided by is with remainder of the problem here is that the answer is in two partsthe integer quotient and the remainder and neither of these results is the same as the decimal result python has separate operations to generate each part python uses the doubled division symbol /for the operation that produces just the integer quotientand introduces the symbol for the operation of finding the remainder try each in the shell / // % now predict and then try each of // % % // % / finding remainders will prove more useful than you might think in the futureoptional from here to the end of the sectionconsidering negative numbers in integer quotients and remaindersin grade school you were probably always doing such remainder calculations with positive integersas we have above this is all we are liklely to need for this course howeverthe remainder operation is defined for all integerseven negative divisor we will probably not need it in this coursebut try - - - - you can stop here and just beware mixing in negative numbers in your integer arithmeticor go on to fuller explanationgo back to positive numbers first divided by // is is the basic relationship is * dividend quotient divisor remainder we want that to always be true the issue is really with integer division when the dividend and divisor are not both positivethe value of this determines the remaindersolving aboveremainder dividend quotient divisor with positive numbers the integer quotient is always no bigger than the real quotient in its definitionpython requires that this is trueno matter what the signs of the operands /(- is - so //(- must be - (not greater than - )by the general relationship between quotients and remaindersthat forces (- (- )*(- - swapping the negative signs- is still - so - / is still - beginning with python |
10,330 | but now look at the remainder formula- % - (- )* last sign switchboth negative - (- is so - /(- is remainder formula- (- - ( )*(- - note the sign of nonzero remainders alway matches the sign of the divisor in python side notemany other languages (javac++use different definition for integer divisionsaying its magnitude is never larger than the real division this forces the remainders for mixed sign divisions to be different than in python example where this is significantin python you can identify an arbitrary odd number because it has remainder when dividing by this is true in python whether the odd number is positive or negativebut it is not true in the other languages stringspart enough with numbers for while strings of characters are another important type in python string delimiterspart string in python is sequence of characters for python to recognize sequence of characterslike helloas stringit must be enclosed in quotes to delimit the string for this whole section on stringscontinue trying each set-off line of code in the shell try "hellonote that the interpreter gives back the string with single quotes python does not care what system you use try 'hi!having the choice of delimiters can be handy figure out how to give python the string containing the texti' happy try it if you got an errortry it with another type of quotesand figure out why that one works and not the first there are many variations on delimiting strings and embedding special symbols we will consider more ways later in strings part ii (page notea string can have any number of characters in itincluding the empty string is '(two quote characters with nothing between themmany beginners forget that having no characters in the middle is legal it can be useful strings are new python type try type('dog'type(' 'type( the last two lines show how easily you can get confusedstrings can include any charactersincluding digits quotes turn even digits into strings this will have consequences in the next section stringspart |
10,331 | string concatenation strings also have operation symbols try in the shell (noting the space after very)'very 'hotthe plus operation with strings means concatenate the strings python looks at the type of operands before deciding what operation is associated with the think of the relation of addition and multiplication of integersand then guess the meaning of *'very 'hotwere you rightthe ability to repeat yourself easily can be handy predict the following and then test remember the last section on types + ' '+' python checks the types and interprets the plus symbol based on the type try ' '+ with mixed string and int typespython sees an ambiguous expressionand does not guess which you want it just gives an error this is traceback error these occur when the code is being executed in the last two lines of the traceback it shows the python line where the error was foundand then reason for the error not all reasons are immediately intelligible to starting programmerbut they are certainly worth checking out in this case it is pretty direct you need to make an explicit conversionso both are strings if you mean concatenation' str( )or so both are int if you mean additionint(' ' with literal strings these examples are only useful for illustrationthere is no reason to write such verbose expressions when you already know the intended result with variablesstarting in the next sectionexpressions involving these conversions become more important string exercise figure out compact way to get python to make the string'yesyesyesyesyes'and try it how about 'maybemaybemaybeyesyesyesyesyes'hint variables and assignment each set-off line in this section should be tried in the shell try width nothing is displayed by the interpreter after this entryso it is not clear anything happened something has happened this is an assignment statementwith variablewidthon the left variable is name for value an assignment statement associates variable name on the left of the equal sign with the value of an expression calculated from the right of the equal sign enter be careful if you are java or cprogrammerthis is unlike those languageswhere the would be automatically converted to ' so the concatenation would make sense hint for the second oneuse two *' and beginning with python |
10,332 | width once variable is assigned valuethe variable can be used in place of that value the response to the expression width is the same as if its value had been entered the interpreter does not print value after an assignment statement because the value of the expression on the right is not lost it can be recovered if you likeby entering the variable name and we did above try each of the following linesheight area width height area the equal sign is an unfortunate choice of symbol for assignmentsince python' usage is not the mathematical usage of the equal sign if the symbol had appeared on keyboards in the early 'sit would probably have been used for assignment instead of =emphasizing the asymmetry of assignment in mathematics an equation is an assertion that both sides of the equal sign are alreadyin factequal python assignment statement forces the variable on the left hand side to become associated with the value of the expression on the right side the difference from the mathematical usage can be illustrated try width so this is not equivalent in python to width the left hand side must be variableto which the assignment is made reversedwe get syntax error try width width this isof coursenonsensical as mathematicsbut it makes perfectly good sense as an assignmentwith the right-hand side calculated first can you figure out the value that is now associated with widthcheck by entering width in the assignment statementthe expression on the right is evaluated first at that point width was associated with its original value so width had the value of which is that value was then assigned to the variable on the left (width againto give it new value we will modify the value of variables in similar way routinely assignment and variables work equally well with strings tryfirst 'suelast 'wongname first last name try enteringfirst fred note the different form of the error message the earlier errors in these tutorials were syntax errorserrors in translation of the instruction in this last case the syntax was legalso the interpreter went on to execute the instruction only then did it find the error described there are no quotes around fredso the interpreter assumed fred was an identifierbut the name fred was not defined at the time the line was executed it is both easy to forget quotes where you need them for literal string and to mistakenly put them around variable name that should not have themtry in the shellfred 'frederickfirst fred first variables and assignment |
10,333 | there fredwithout the quotesmakes sense there are more subtleties to assignment and the idea of variable being "name fora valuebut we will worry about them laterin issues with mutable objects (page they do not come up if our variables are just numbers and strings autocompletiona handy short cut idle remembers all the variables you have defined at any moment this is handy when editing without pressing entertype into the shell just windows usersthen hold down the alt key and press the key this key combination is abbreviated alt-mac usersthe windows key combination above may give you funny character (if so backspace over it in that case you need to hold down both the control key and the alt/option key when pressing the '/this may hold in other places in this tutorialwhere the alt key is called for in windows assuming you are following on the earlier variable entries to the shellyou should see autocompleted to be first this is particularly useful if you have long identifiersyou can press alt-several times if more than one identifier starts with the initial sequence of characters you typed if you press alt-again you should see fred backspace and edit so you have fiand then and press alt-again you should not see fred this timesince it does not start with fi literals and identifiers expressions like or 'helloare called literalscoming from the fact that they literally mean exactly what they say they are distinguished from variableswhose value is not directly determined by their name the sequence of characters used to form variable name (and names for other python entities lateris called an identifier it identifies python variable or other entity there are some restrictions on the character sequence that make up an identifierthe characters must all be lettersdigitsor underscores _and must start with letter in particularpunctuation and blanks are not allowed there are some words that are reserved for special use in python you may not use these words as your own identifiers they are easy to recognize in idlebecause they are automatically colored orange for the curiousyou may read the full listfalse none true and as assert async await break class continue def del elif else except finally for from global if import in is lambda nonlocal not or pass raise return try while with yield there are also identifiers that are automatically defined in pythonand that you could redefinebut you probably should not unless you really know what you are doingwhen you start the editorwe will see how idle uses color to help you know what identifies are predefined python is case sensitivethe identifiers lastlastand last are all different be sure to be consistent using the alt-auto-completion shortcut in idle helps ensure you are consistent what is legal is distinct from what is conventional or good practice or recommended meaningful names for variables are important for the humans who are looking at programsunderstanding themand revising them that sometimes means you would like to use name that is more than one word longlike price at openingbut blanks are beginning with python |
10,334 | illegalone poor option is just leaving out the blankslike priceatopening then it may be hard to figure out where words split two practical options are underscore separatedputting underscores (which are legalin place of the blankslike price_at_opening using camel-caseomitting spaces and using all lowercaseexcept capitalizing all words after the firstlike priceatopening use the choice that fits your taste (or the taste or convention of the people you are working with print functionpart in interactive use of the python interpreteryou can type an expression and immediately see the result of its evaluation this is fine to test out syntax and maybe do simple calculator calculations in program run from file like the first sample programpython does not display expressions this way if you want your program to display somethingyou can give explicit instructions with the print function try in the shellx print('the sum of' 'plus' 'is' +ythe print function will prints as strings everything in comma-separated sequence of expressionsand it will separate the results with single blanksand advance to the next line at the endby default note that you can mix typesanything that is not already string is automatically converted to its string representation you can also use it with no parametersprint(to only advance to the next line strings part ii triple quoted string literals strings delimited by one quote characterlike 'are required to lie within single python line it is sometimes convenient to have multi-line stringwhich can be delimited with triple quotes''try typing the following you will get continuation lines until the closing triple quotes try in the shellsillytest '''say" ' in!this is line ''print(sillytestthe line structure is preserved in multi-line string as you can seethis also allows you to embed both single and double quote charactersescape codes continuing in the shell with sillytestenter just sillytest print functionpart |
10,335 | the answer looks strangeit indicates an alternate way to encode the string internally in python using escape codes escape codes are embedded inside string literals and start with backslash character they are used to embed characters that are either unprintable or have special syntactic meaning to python that you want to suppress in this example you see some of the ones in this short list of most common escape codesescape code \\ \\meaning (backslashnewline (single quote character(double quote characterthe newline character indicates further text will appear on new line when printed when you use the print functionyou get the actual printed meaning of the escape coded character predict the resultand try in the shellprint(' \nb\ \nc'did you guess the right number of lines splitting in the right places the idle editor and execution loading program in the idle editorand running it it is time to put longer collections of instructions together that is most easily done by creating text file and running the python interpreter on the file idle simplifies that process first you can put an existing file into an idle edit window start with the sample program madlib py if you have not downloaded it yetsee your python folder and python examples (page assuming you are already in idle from the previous sectionsyou can open file from thereclick on the idle file menu and select open (or as you seeyou can use the shortcut ctrl- that means holding down the ctrl keyand pressing the letter for open you should get file selection dialog you need to navigate to the folder with the file you want if you already had file openand its window has the foreground focus when you make access the file menuthen the folder that opens is the same as the folder from which the current file came if the shell window has the foreground focusthen the folder opened depends on the operating systemwindowsat least through python windows is likely to open buried system folder that you do not want to mess withswitch to your desktop or documentsand find the right folder from there hopefully the behaviour will be more like on mac in future version mac and linuxa reasonable folder opensdocuments navigate from there hence it is important to set the focus on an edit window to have the same folder appear when opening new file select the file you want (the initial suggestion was madlib py you will see the source code again now run this program from inside of idlego to the run menu of that edit windowand select run module notice the shortcut ( also available if the shell window does not automatically come to the foregroundselect it you should see line saying restart and then the start of the execution of the mad lib program with the cursor waiting for your entry after the first prompt finish executing the program be sure to type the final requested enterso you get back to the interpreter prompt beginning with python |
10,336 | look at the editor window again you should see that different parts of the code have different colors string literals are likely green the reserved word def is likely orange look at the last two lineswhere the identifier tellstory is blackand the identifier input is likely purple only identifiers that are not predefined by python are black if you create an identifier namemake sure idle shows it in black starting idle for editing you are strongly suggested to keep the programs you write in the given examples folder along with all the examples provided to you you can always easily see the files you createdall togetherby sorting by creation date you are likely to create new programs derived from some of the given examplesand some earlier programs of your own everything is easy to access if you keep them together the way recommended to start idle to work on this tutorial is to start by opening it on file in the folder where you want to workeither file you want to further edita related file you want to modifyor just any python file in the same folder if you want to start from scratch to open idle with an initial file to editselect the python file in an operating system windowright click (windowsor control-click (mac)to get pop-up window to select how to open the file on windowsthe line for idle requires you to open sub-menu select idle for the latest version opening idle without file referencedirectly from the operating systemmakes the associated folder for opening and saving files be the same wrong one as described in the previous section from inside idlewhen the shell window has foreground focus alternate approaches to starting idle are discussed in the operating specific appendix sections the classic first program have idle started as in the previous sectionso some python file has the foreground focus open new window by going to the file menu and selecting new file this gives you rather conventional text editing window with the mouse availableability to cut and pasteplus few special options for python type (or pastethe following into the editor window (not the shell window)print('hello world!'save the file with the menu sequence file saveand then enter the file name hello py python program files should always be given name ending in pyif you give no extensionpyis assumed you can also enter it explicitly there are also the options file save as and file save copy as both save copy to different namebut only file save as changes the name of the file you are editing in idle warningit is the contents of the foreground idle window that get saved you are unlikely to mean to save the contents of the shell windowbut it is easy for that window to have the focus when you mean to save program in an edit window syntax coloringif you look in the editoryou should see that your text is color coded the editor will color different parts of python syntax in special colors now that you have completesaved programchoose run run module you should see the program run in the python shell window you just wrote and executed program unlike when you use the shellthis code is saved to file in your python folder you can open and execute the file any time you want (in idleuse file open the idle editor and execution |
10,337 | to the interpretera program source file is python module we will tend to use the more general terma program file is module note the term from the menu when running the program distinguish program code from shell textit is easy to confuse the shell and the edit windows make sure you keep them straight the hello py program is just the line print('hello world!'that you typed into the edit window and saved when you ran the program in idleyou saw results in the shell first came the restart noticethe one-line output from the program saying helloand further shell prompt===============================restart =======hello worldyou could also have typed this single printing line directly in the shell in response to shell prompt when you see you could enter the print function and get the exchange between you and the shellprint('hello world'hello worldwarningthe three lines above are not program you could save in file and run this is just an exchange in the shellwith its promptsindividual line to executeand the response againjust the single linewith no print('hello world!'entered into the edit window forms program you can save and run the prompts have no place in python program file we will shortly get to more interesting many-statement programswhere it is much more convenient to use the edit window than the shellthe general assumption in this tutorial will be that programs are run in idle and the idle shell is the shell referred to it will be explicitly stated when you should run program directly from the operating system in general it is also fine to run our programs from cmd console (windowsor terminal (macor from different development environment warningrunning the text based example programs in windowslike birthday pyby selecting them to run from file folderwill not work wellthe program ends and the window automatically closes before you can see the final output on mac you get to explicitly close the verbose terminal window created when you run python program from the finder program documentation string the hello program above is self evidentand shows how short and direct program can be (unlike other languages such as javastillright awayget used to documenting program python has special featureif the beginning of program is just quoted stringthat string is taken to be the program' documentation string open the example file hello py in the edit window''' very simple programshowing how short python program can be beginning with python |
10,338 | authors______ ''print('hello world!'#this is stupid comment after the mark most commonlythe initial documentation goes on for several linesso multi-line string delimiter is used (the triple quotesjust for completeness of illustration in this programanother form of comment is also showna comment that starts with the symbol and extends to the end of the line the python interpreter completely ignores this form of comment such comment should only be included for better human understanding avoid making comments that do not really aid human understanding (do what saynot what did above good introductory comment strings and appropriate names for the parts of your programs make fewer symbol comments neededrun the program and see the documentation and comment make no difference in the result screen layout of course you can arrange the windows on your computer screen any way that you like suggestion is to display the combination of the editor to writethe shell to runand the tutorial to follow along there is an alternative to maximization for the idle editor windowit you want it to go top to bottom of the screen but not widenyou can toggle that state with options -zoom height or the keyboard shortcut shown beside it input and output the input function the hello program of the classic first program (page always does the same thing this is not very interesting programs are only going to be reused if they can act on variety of data one way to get data is directly from the user modify the hello py program as follows in the editorand save it with file save as 'using the name hello_you py person input('enter your name'print('hello'personrun the program in the shell you should see enter your namemake sure the typing cursor is in the shell windowat the end of this line then follow the instruction (and press enterafter you type your responseyou can see that the program has taken in the line you typed that is what the built-in function input doesfirst it prints the string you give as parameter (in this case 'enter your name')and then it waits for line to be typed inand returns the string of characters you typed in the hello_you py program this value is assigned to the variable personfor use later the parameter inside the parentheses after input is important it is promptprompting you that keyboard input is expected at that pointand hopefully indicating what is being requested without the promptthe user would not know what was happeningand the computer would just sit there waitingopen the example programinterview py before running it (with any made-up data)see if you can figure out what it will do'''illustrate input and print ''applicant input("enter the applicant' name"interviewer input("enter the interviewer' name" input and output |
10,339 | time input("enter the appointment time"print(interviewer"will interview"applicant"at"timethe statements are executed in the order they appear in the text of the programsequentially this is the simplest way for the execution of the program to flow you will see instructions later that alter that natural flow if we want to reload and modify the hello_you py program to put an exclamation point at the endyou could tryperson input('enter your name'print('hello'person'!'run it and you see that it is not spaced right there should be no space after the person' namebut the default behavior of the print function is to have each field printed separated by space there are several ways to fix this you should know one think about it before going on to the next section hint print with keyword parameter sep one way to put punctuation but no space after the person in hello_you py is to use the plus operatoranother approach is to change the default separator between fields in the print function this will introduce new syntax featurekeyword parameters the print function has keyword parameter named sep if you leave it out of call to printas we have so farit is set equal to space by default if you add final fieldsep=''in the print function in hello_you pyyou get the following example filehello_you py'''hello to you''illustrates sep with empty string in print person input('enter your name'print('hello 'person'!'sep=''try the program keyword parameters must be listed at the end of the parameter list they have the keyword namefollowed by an equal signbefore the value being given we will see another example shortly it is standard python convention that when giving keyword and valuethe equal sign has no space on either side (this is the only place you are not encouraged to set off an equal sign with spaces numbers and strings of digits consider the following problemprompt the user for two numbersand then print out sentence stating the sum for instance if the user entered and you would print 'the sum of and is you might imagine solution like the example file addition pyshown below there is problem can you figure it out before you try running ithint '''error in addition from input '' input("enter number" input("enter second number"print('the sum of 'xand 'yis ' + 'sep=''#error end up running it in any case we do not want string concatenationbut integer addition we need integer operands briefly mentioned in whirlwind introduction to types and functions (page was the fact that we can use type names as functions to convert types the operation on strings adds no extra space the input function produces values of string type beginning with python |
10,340 | one approach would be to do that further variable names are also introduced in the example addition py file below to emphasize the distinctions in types read and run'''conversion of strings to int before addition''xstring input("enter number" int(xstringystring input("enter second number" int(ystringprint('the sum of 'xand 'yis ' + 'sep=''needing to convert string input to numbers is common situationboth with keyboard input and later in web pages while the extra variables above emphasized the stepsit is more concise to write as in the variation in example fileaddition pydoing the conversions to type int immediately'''two numeric inputswith immediate conversion'' int(input("enter number") int(input("enter second number")print('the sum of 'xand 'yis ' + 'sep=''the simple programs so far have followed basic programming patterninput-calculate-output get all the data firstcalculate with it secondand output the results last the pattern sequence would be even clearer if we explicitly create named result variable in the middleas in addition py '''two numeric inputsexplicit sum'' int(input("enter an integer") int(input("enter another integer")sum + print('the sum of 'xand 'yis 'sum'sep=''we will see more complicated patternswhich involve repetitionin the future exercise for addition write versionadd pythat asks for three numbersand lists all threeand their sumin similar format to addition py displayed above exercise for quotients write programquotient pythat prompts the user for two integersand then prints them out in sentence with an integer division problem in form just like the quotient of and is with remainder of review division and remainders (page if you forget the integer division or remainder operator string format operation in grade school quizzes common convention is to use fill-in-the blanks for instancehello and you can fill in the name of the person greetedand combine given text with chosen insertion we use this as an analogypython has similar constructionbetter called fill-in-the-braces there is particular operation on strings input and output |
10,341 | called formatthat makes substitutions into places enclosed in braces for instance the example filehello_you pycreates and prints the same string as in hello_you py from the previous section'''hello to you''illustrates format with {in print person input('enter your name'greeting 'hello{}!format(personprint(greetingthere are several new ideas herefirst method calling syntax for objects is used you will see this very important modern syntax in more detail at the beginning of the next in object orientation (page all data in python are objectsincluding strings objects have special syntax for functionscalled methodsassociated with the particular type of object in particular str objects have method called format the syntax for methods has the object followed by period followed by the method nameand any further parameters in parentheses object methodname(parametersin the example abovethe object is the string 'hello {}!the method is named format there is one further parameterperson the string for the format method has special formwith braces embedded places where braces are embedded are replaced by the value of an expression taken from the parameter list for the format method there are many variations on the syntax between the braces in this case we use the syntax where the first (and onlylocation in the string with braces has substitution made from the first (and onlyparameter in the code abovethis new string is assigned to the identifier greetingand then the string is printed the identifier greeting was introduced to break the operations into clearer sequence of steps howeversince the value of greeting is only referenced onceit can be eliminated with the more concise versionperson input('enter your name'print('hello {}!format(person)consider the interview program suppose we want to add period at the end of the sentence (with no space before itone approach would be to combine everything with plus signs another way is printing with keyword sep='another approach is with string formatting using our grade school analogythe idea is to fill in the blanks in will interview at there are multiple places to substituteand the format approach can be extended to multiple substitutionseach place in the format string where there is '{}'the format operation will substitute the value of the next parameter in the format parameter list run the example file interview pyand check that the results from all three methods match '''compare print with concatenation and with format string ''applicant input("enter the applicant' name"interviewer input("enter the interviewer' name"time input("enter the appointment time"print(interviewer will interview applicant at time +'print(interviewerwill interview 'applicantat 'time'sep=''print('{will interview {at {format(interviewerapplicanttime)sometimes you want single stringbut not just for printing you can combine pieces with the operatorbut then all pieces must be strings or explicitly converted to strings an advantage of the format method is that it will convert types to string automaticallylike the print function here is another variant of our addition sentence exampleaddition pyusing the format method beginning with python |
10,342 | '''two numeric inputsexplicit sum'' int(input("enter an integer") int(input("enter another integer")sum + sentence 'the sum of {and {is {format(xysumprint(sentenceconversion to strings was not needed in interview py (everything started out as string in addition pyhoweverthe automatic conversion of the integers to strings is useful so far there is no situation that requires format string instead of using other approaches sometimes format string provides shorter and simpler expression except where specifically instructed in an exercise for practiceuse whatever approach to combining strings and data that you like there are many elaborations to the fields in braces to control formatting we will look at one laterstring formats for float precision (page )where format strings are particularly useful technical pointsince braces have special meaning in format stringthere must be special rule if you want braces to actually be included in the final formatted string the rule is to double the braces'{{and '}}the example code formatbraces pyshown belowmakes setstr refer to the string 'the set is { , the initial and final doubled braces in the format string generate literal braces in the formatted string'''illustrate braces in formatted string '' setstr 'the set is {{{}{}}format(abprint(setstrthis kind of format string depends directly on the order of the parameters to the format method there is another approach with dictionarythat was used in the first sample programmadlib pyand will be discussed more in dictionaries and string formatting (page the dictionary approach is probably the best in many casesbut the count-based approach is an easier startparticularly if the parameters are just used oncein order optional elaboration with explicitly numbered entries imagine the format parameters numbered in orderstarting from in this case and the number of the parameter position may be included inside the bracesso an alternative to the last line of interview py is (added in example file interview py)print('{ will interview { at { format(interviewerapplicanttime)this is more verbose than the previous versionwith no obvious advantage howeverif you desire to use some of the parameters more than oncethen the approach with the numerical identification with the parameters is useful every place the string includes '{ }'the format operation will substitute the value of the initial parameter in the list wherever '{ }appearsthe next format parameter will be substituted predict the results of the example file arith py shown belowif you enter and then check yourself by running it in this case the numbers referring to the parameter positions are necessary they are both repeated and used out of order'''fancier format string example with parameter identification numbers -useful when some parameters are used several times '' int(input('enter an integer') int(input('enter another integer')formatstr '{ { { }{ { { equations formatstr format(xyx+yx*yprint(equations input and output |
10,343 | try the program with other data now that you have few building blocksyou will see more exercises where you need to start to do creative things you are encouraged to go back and reread learning to problem-solve (page addition format exercise write version of exercise for addition (page )add pythat uses the string format method to construct the same final string as before quotient format exercise write version of the quotient problem in exercise for quotients (page )quotientformat pythat uses the string format method to construct the same final string as before again be sure to give full sentence including the initial numbers and both the integer quotient and the remainder defining functions of your own syntax template typography when new python syntax is introducedthe usual approach will be to give both specific examples and general templates in general templates for python syntax the typeface indicates the the category of each parttypeface typewriter font emphasized bold meaning text to be written verbatim example sep=' place where you can use an arbitrary expression place where you can use an arbitrary identifier normal text description of what goes in that position,without giving explicit syntax integervalue variablename digit - more complete example of using this typography with several parts would be description of an assignment statementvariablename someexpression with an arbitrary identifierthe specific symbol =and an expression try to make the parts that are not verbatim to be descriptive of the expected use will use these conventions shortly in the discussion of function syntaxand will continue to use the conventions throughout the tutorial first function definition if you know it is the birthday of friendemilyyou might tell those gathered with you to sing "happy birthday to emilywe can make python display the song readand run if you likethe example program birthday py beginning with python |
10,344 | print("happy birthday to you!"print("happy birthday to you!"print("happy birthdaydear emily "print("happy birthday to you!"you would probably not repeat the whole song to let others know what to sing you would give request to sing via descriptive name like "happy birthday to emilyin python we can also give name like happybirthdayemilyand associate the name with whole song by using function definition we use the python def keywordshort for define read for now def happybirthdayemily()#program does nothing as written print("happy birthday to you!"print("happy birthday to you!"print("happy birthdaydear emily "print("happy birthday to you!"there are several parts of the syntax for function definition to noticeline the heading contains defthe name of the functionparenthesesand finally colon more general syntax is def function_name()lines - the remaining lines form the function body and are indented by consistent amount (the exact amount is not important to the interpreterthough or spaces are common conventions the whole definition does just thatdefines the meaning of the name happybirthdayemilybut it does not do anything else yet for examplethe definition itself does not make anything be printed yet this is our first example of altering the order of execution of statements from the normal sequential order notethe statements in the function definition are not executed as python first passes over the lines the code above is in example file birthday py load it in idle and execute it from there nothing should happen visibly this is just like defining variablepython just remembers the function definition for future reference after idle finished executing programhoweverits version of the shell remembers function definitions from the program in the idle shell (not the editor)enter happybirthdayemily the result probably surprises youwhen you give the shell an identifierit tells you its value abovewithout parenthesesit identifies the function code as the value (and gives location in memory of the codenow try the name in the idle shell with parentheses addedhappybirthdayemily(the parentheses tell python to execute the named function rather than just refer to the function python goes back and looks up the definitionand only thenexecutes the code inside the function definition the term for this action is function call or function invocation notein the function call there is no defbut there is the function name followed by parentheses function_name( defining functions of your own |
10,345 | in many cases we will use feature of program execution in idlethat after program execution is completedthe idle shell still remembers functions defined in the program this is not true if you run program by selecting it directly in the operating system look at the example program birthday py see it just adds two more linesnot indented can you guess what it doestry it '''function definition and invocation '' def happybirthdayemily()print("happy birthday to you!"print("happy birthday to you!"print("happy birthdaydear emily "print("happy birthday to you!" happybirthdayemily(happybirthdayemily(the execution sequence is different from the textual sequence lines - python starts from the topreading and remembering the definition the definition ends where the indentation ends (the code also shows blank line therebut that is only for humansto emphasize the end of the definition line this is not indented inside any definitionso the interpreter executes it directlycalling happybirthdayemily(while remembering where to return lines - the code of the function is executed for the first timeprinting out the song end of line back from the function call continue on line the function is called again while this location is remembered lines - the function is executed againprinting out the song again end of line back from the function callbut at this point there is nothing more in the programand execution stops functions alter execution order in several waysby statements not being executed as the definition is first readand then when the function is called during executionjumping to the function codeand back at the the end of the function execution if it also happens to be andre' birthdaywe might define function happybirthdayandretoo think how to do that before going on multiple function definitions here is example program birthday py where we add function happybirthdayandreand call them both guess what happensand then try it'''function definitions and invocation ''def happybirthdayemily()print("happy birthday to you!"print("happy birthday to you!"print("happy birthdaydear emily "print("happy birthday to you!"def happybirthdayandre()print("happy birthday to you!" beginning with python |
10,346 | print("happy birthday to you!"print("happy birthdaydear andre "print("happy birthday to you!"happybirthdayemily(happybirthdayandre(againeverything is definitions except the last two lines they are the only lines executed directly the calls to the functions happen to be in the same order as their definitionsbut that is arbitrary if the last two lines were swappedthe order of operations would change do swap the last two lines so they appear as belowand see what happens when you execute the programhappybirthdayandre(happybirthdayemily(functions that you write can also call other functions you write it is good convention to have the main action of program be in function for easy reference the example program birthday py has the two happy birthday calls inside final functionmain do you see that this version accomplishes the same thing as the last versionrun it '''function definitions and invocation '' def happybirthdayemily()print("happy birthday to you!"print("happy birthday to you!"print("happy birthdaydear emily "print("happy birthday to you!" def happybirthdayandre()print("happy birthday to you!"print("happy birthday to you!"print("happy birthdaydear andre "print("happy birthday to you!" def main()happybirthdayemily(happybirthdayandre( main(if we want the program to do anything automatically when it is runswe need one line outside of definitionsthe final line is the only one directly executedand it calls the code in mainwhich in turn calls the code in the other two functions detailed order of execution lines - definitions are read and remembered line the only statement outside definitionsis executed directly this location is remembered as main is executed line start on main line this location is remembered as execution jumps to happybirthdayemily lines - are executed and emily is sung to return to the end of line back from happybirthdayemily function call line now happybirthdayandre is called as this location is remembered lines - sing to andre defining functions of your own |
10,347 | return to the end of line back from happybirthdayandre function calldone with main return to the end of line back from mainat the end of the program there is one practical difference from the previous version after executionif we want to give another round of happy birthday to both personswe only need to enter one further call in the shell tomain(as simple example emphasizing the significance of line being indentedguess what the the example file order py doesand run it to checkdef ()print('in function 'print('when does this print?' (modify the file so the second print function is outdented like below what should happen nowtry itdef ()print('in function 'print('when does this print?' (the lines indented inside the function definition are remembered firstand only executed when the function is invoked at the end the lines outside any function definition (not indentedare executed in order of appearance poem function exercise write programpoem pythat defines function that prints short poem or song verse give meaningful name to the function have the program end by calling the function three timesso the poem or verse is repeated three times function parameters as young childyou probably heard happy birthday sung to couple of peopleand then you could sing to new personsay mariawithout needing to hear the whole special version with maria' name in it word for word you had the power of abstraction with examples like the versions for emily and andreyou could figure out what change to make it so the song could be sung to mariaunfortunatelypython is not that smart it needs explicit rules if you needed to explain explicitly to someone how happy birthday worked in generalrather than just by exampleyou might say something like thisfirst you have to be given person' name then you sing the song with the person' name inserted at the end of the third line python works something like thatbut with its own syntax the term "person' nameserves as stand-in for the actual data that will be used"emily""andre"or "mariathis is just like the association with variable name in python "person' nameis not legal python identifierso we will use just person as this stand-in the function definition indicates that the variable name person will be used inside the function by inserting it between the parentheses of the definition then in the body of the definition of the functionperson is used in place of the real data for any specific person' name read and then run example program birthday py '''function with parameter '' def happybirthday(person)print("happy birthday to you!"print("happy birthday to you!" beginning with python |
10,348 | print("happy birthdaydear person "print("happy birthday to you!" happybirthday('emily'happybirthday('andre'in the definition heading for happybirthdayperson is referred to as formal parameter this variable name is placeholder for the real name of the person being sung to the last two lines of the programagainare the only ones outside of definitionsso they are the only ones executed directly there is now an actual name between the parentheses in the function calls the value between the parentheses here in the function call is referred to as an argument or actual parameter of the function call the argument supplies the actual data to be used in the function execution when the call is madepython does this by associating the formal parameter name person with the actual parameter dataas in an assignment statement in the first callthis actual data is 'emilywe say the actual parameter value is passed to the function the execution in greater detail lines - definition remembered line call to happybirthdaywith actual parameter 'emily line 'emilyis passed to the functionso person 'emily lines - the song is printedwith 'emilyused as the value of person in line printing happy birthdaydear emily end of line after returning from the function call line call to happybirthdaythis time with actual parameter 'andre line 'andreis passed to the functionso person 'andre lines - the song is printedwith 'andreused as the value of person in line printing happy birthdaydear andre end of line after returning from the function calland the program is over notebe sure you completely understand birthday py and the sequence of executionit illustrates extremely important ideas that many people miss the first timeit is essential to understand the difference between defining function (lines - with the def heading including formal parameter nameswhere the code is merely instructions to be rememberednot acted on immediately calling function with actual parameter values to be substituted for the formal parameters and have the function code actually run when the instruction containing the call is run also note that the function can be called multiple times with different expressions as the actual parameters (line and again in line the beauty of this system is that the same function definition can be used for call with different actual parameterand then have different effect the value of the formal parameter person is used in the third line of happybirthdayto put in whatever actual parameter value was given notethis is the power of abstraction it is one application of the most important principal in programming rather than have number of separately coded parts with only slight variationssee where it is appropriate to combine them have given the explicit terminology "formal parameterand "actual parameterin various places you may see either of these terms replaced by just "parameteror maybe "argumentin that case you must determine from context which is being discusseda definition and formal parameter or function call and an actual parameter defining functions of your own |
10,349 | using function whose parameters refer to the parts that are different in different situations then the code is written to be simultaneously appropriate for the separate specific situationswith the substitutions of the right parameter values you can go back to having main function againand everything works run birthday py'''function with parameter called in main''def happybirthday(person)print("happy birthday to you!"print("happy birthday to you!"print("happy birthdaydear person "print("happy birthday to you!"def main()happybirthday('emily'happybirthday('andre'main(in birthday pythe function calls in lines and were outside any function definitionso they did actually lead to immediate execution of the function in birthday py the calls to happybirthday are inside another function definition (main)so they are not actually run until the function main is run (from the last lineoutside any functionsee birthday function exercise (page we can combine function parameters with user inputand have the program be able to print happy birthday for anyone check out the main method and run birthday_who py '''user input supplies function parameter'' def happybirthday(person)print("happy birthday to you!"print("happy birthday to you!"print("happy birthdaydear person "print("happy birthday to you!" def main()username input("enter the birthday person' name"happybirthday(username main(this last version illustrates several important ideas there are more than one way to get information into function(ahave value passed in through parameter (from line to line (bprompt the userand obtain data from the keyboard (line it is good idea to separate the internal processing of data from the external input from the user by the use of distinct functions here the user interaction is in mainand the data is manipulated in happybirthday in the first examples of actual parameterswe used literal values in general an actual parameter can be an expression the expression is evaluated before it is passed in the function call one of the simplest expressions is plain variable namewhich is evaluated by replacing it with its associated value since it is only the value of the actual parameter that is passednot any variable namethere is no need to have variable name used in an actual parameter match formal parameter name (here we have the value of username in main becoming the value of person in happybirthday beginning with python |
10,350 | now that we have nested function callsit is worth looking further at tracebacks from execution errors if add line to main in birthday pyhappybirthday( as in example file birthdaybad pyand then run ityou get something close totraceback (most recent call last)file "/hands-on/examples/birthdaybad py"line in main(file "/hands-on/examples/birthdaybad py"line in main happybirthday( file "/hands-on/examples/birthdaybad py"line in happybirthday print("happy birthdaydear person "typeerrorcan' convert 'intobject to str implicitly your file folder is probably different than /hands-on/examples the last three lines are most importantgiving the line number where the error was detectedthe text of the line in questionand description of what problem was found often that is all you need to look atbut this example illustrates that the genesis of the problem may be far away from the line where the error was detected going further up the tracebackyou find the sequence of function calls that led to the line where the error was detected you can see that in main call happybirthday with the bad parameter birthday function exercise make your own further change to birthday py and save it as birthdaymany pyadd function call (but not another function definition)so maria gets versein addition to emily and andre also print blank line between verses (you may either do this by adding print line to the function definitionor by adding print line between all calls to the function multiple function parameters function can have more than one parameter in parameter list separated by commas here the example program addition py changes example program addition pyusing function to make it easy to display many sum problems read and follow the codeand then run'''display any number of sum problems with function handle keyboard input separately ''def sumproblem(xy)sum sentence 'the sum of {and {is {format(xysumprint(sentencedef main()sumproblem( sumproblem( int(input("enter an integer") int(input("enter another integer")sumproblem(abmain( defining functions of your own |
10,351 | the actual parameters in the function call are evaluated left to rightand then these values are associated with the formal parameter names in the function definitionalso left to right for example function call with actual parametersf(actual actual actual )calling function with definition headingdef (formal formal formal )acts approximately as if the first lines executed inside the called function were formal actual formal actual formal actual functions provide extremely important functionality to programsallowing tasks to be defined once and performed repeatedly with different data it is essential to see the difference between the formal parameters used to describe what is done inside the function definition (like and in the definition of sumproblemand the actual parameters (like and or and which substitute for the formal parameters when the function is actually executed the main method above uses three different sets of actual parameters in the three calls to sumproblem quotient function exercise the example addition py is modification of addition pyputting the arithmetic problem into function and then calling the function several times with different parameters similarly modify quotientformat py from quotient format exercise (page and save it as quotientprob py you should create function quotientproblem with numerical parameters like in all the earlier versionsit should print full sentence containing the inputsquotientand remainder the main method in the new program should test the quotientproblem function on several sets of literal valuesand also test the function with input from the user returned function values you probably have used mathematical functions in algebra classthey all had calculated values associated with them for instance if you defined ( )= then it follows that ( is and ( )+ ( is function calls in expressions get replaced during evaluation by the value of the function the corresponding definition and examples in python would be the followingtaken from example program return py read and run''' simple function returning valueused in an expression''def ( )return * print( ( )print( ( ( )the new python syntax is the return statementwith the word return followed by an expression functions that return values can be used in expressionsjust like in math class when an expression with function call is evaluatedthe function call is effectively replaced temporarily by its returned value inside the python function definitionthe value to be returned is given by the expression in the return statement after the function finishes executing from inside print( ( ) beginning with python |
10,352 | it is as if the statement temporarily became print( and similarly when executing print( ( ( )the interpreter first evaluates ( and effectively replaces the call by the returned result as if the statement temporarily became print( ( )and then the interpreter evaluates ( and effectively replaces the call by the returned result as if the statement temporarily became print( resulting finally in being calculated and printed python functions can return any type of datanot just numbersand there can be any number of statements executed before the return statement readfollowand run the example program return py ''' function returning string and using local variable'' def lastfirst(firstnamelastname)separator 'result lastname separator firstname return result print(lastfirst('benjamin''franklin')print(lastfirst('andrew''harrington')the code above has new featurevariables separator and result are given value inside the functionbut separator and result are not among the formal parameters the assignments work as you would expect here more on this shortlyin local scope (page details of the execution lines - remember the definition line call the functionremembering where to return line pass the parametersfirstname 'benjamin'lastname 'franklin line assign the variable separator the value ' line assign the variable result the value of lastname separator firstname which is 'franklin''benjamin'which evaluates to 'franklinbenjamin line return 'franklinbenjamin line use the value returned from the function call so the line effectively becomes print('franklinbenjamin')so print it line call the function with the new actual parametersremembering where to return line pass the parametersfirstname 'andrew'lastname 'harrington lines - calculate and return 'harringtonandrew line use the value returned by the function and print 'harringtonandrew defining functions of your own |
10,353 | compare return py and addition pyfrom the previous section both use functions both printbut where the printing is done differs the function sumproblem prints directly inside the function and returns nothing explicitly on the other hand lastfirst does not print anything but returns string the caller gets to decide what to do with the stringand above it is printed in the main program open addition py againand introduce common mistake change the last line of the function main inserting printso it says print(sumproblem(ab)then try running the program the desired printing is actually done inside the function sumproblem you introduced statement to print what sumproblem returns although sumproblem returns nothing explicitlypython does make every function return something if there is nothing explicitly returnedthe special value none is returned you should see that in the program' shell output this is fairly common error warningif you see 'nonein your printed output where you do not expect itit is likely that you have printed the return value of function that did not return anything explicitlyin generalfunctions should do single thing you can easily combine sequence of functionsand you have more flexibility in the combinations if each does just one unified thing the function sumproblem in addition py does two thingsit creates sentenceand prints it if that is all you haveyou are out of luck if you want to do something different with the sentence string better way is to have function that just creates the sentenceand returns it for whatever further use you want printing is one possibilitydone in addition py'''display sum problems with function returning stringnot printing directly ''def sumproblemstring(xy)sum return 'the sum of {and {is {format(xysumdef main()print(sumproblemstring( )print(sumproblemstring( ) int(input("enter an integer") int(input("enter another integer")print(sumproblemstring(ab)main(quotient string return exercise create quotientreturn py by modifying quotientprob py in quotient function exercise (page so that the program accomplishes the same thingbut everywhere change the quotientproblem function into one called quotientstring that merely returns the string rather than printing the string directly have the main function print the result of each call to the quotientstring function two roleswriter and consumer of functions the remainder of this section covers finer points about functions that you might skip on first reading we are only doing tiny examples so far to get the basic idea of functions in much larger programsfunctions are useful to manage complexitysplitting things up into logically relatedmodest sized pieces programmers are both beginning with python |
10,354 | writers of functions and consumers of the other functions called inside their functions it is useful to keep those two roles separatethe user of an already written function needs to know the name of the function the order and meaning of parameters what is returned or produced by the function how this is accomplished is not relevant at this point for instanceyou use the work of the python development teamcalling functions that are built into the language you need know the three facts about the functions you call you do not need to know exactly how the function accomplishes its purpose on the other hand when you write function you need to figure out exactly how to accomplish your goalname relevant variablesand write your codewhich brings us to the next section local scope for the logic of writing functionsit is important that the writer of function knows the names of variables inside the function on the other handif you are only using functionmaybe written by someone unknown to youyou should not care what names are given to values used internally in the implementation of the function you are calling python enforces this idea with local scope rulesvariable names initialized and used inside one function are invisible to other functions such variables are called local variables for examplean elaboration of the earlier program return py might have its lastfirst function with its local variable separatorbut it might also have another function that defines separator variablemaybe with different value like '\nthey would not conflict they would be independent this avoids lots of errorsfor examplethe following code in the example program badscope py causes an execution error read it and run itand see'''program causing an error with an undefined variable''def main() (def ()print(xerrorf does not know about the defined in main main(we will fix this error below the execution error message mentions "global namenames defined outside any function definitionat the "top-levelof your program are called global they are special case they are discussed more in the next section if you do want local data from one function to go to anotherdefine the called function so it includes parametersread and compare and try the program goodscope py''' change to badscope py avoiding any error by passing parameter''def main() (xdef ( )print(xmain( defining functions of your own |
10,355 | with parameter passingthe parameter name in the function does not need to match the name of the actual parameter in main the definition of could just as well have beendef (whatever)print(whateverglobal constants if you define global variables (variables defined outside of any function definition)they are visible inside all of your functions they have global scope it is good programming practice to avoid defining global variables and instead to put your variables inside functions and explicitly pass them as parameters where needed one common exception is constantsa constant is name that you give fixed data value toby assigning value to the name only in single assignment statement you can then use the name of the fixed data value in expressions later simple example program is constant py'''illustrate global constant being used inside functions ''pi global constant -only place the value of pi is set def circlearea(radius)return pi*radius*radius use value of global constant pi def circlecircumference(radius)return *pi*radius use value of global constant pi def main()print('circle area with radius :'circlearea( )print('circumference with radius :'circlecircumference( )main(this example uses numbers with decimal pointsdiscussed more in decimalsfloatsand floating point arithmetic (page by conventionnames for constants are all capital letters issues with global variables do not come up if they are only used as constants function names defined at the top-level also have global scope this is what allows you to use one function you defined inside another function you definelike calling circlearea from inside main dictionaries definition and use of dictionaries in common usagea dictionary is collection of words matched with their definitions given wordyou can look up its definition python has built in dictionary type called dict which you can use to create dictionaries with arbitrary definitions for character strings it can be used for the common usageas in simple english-spanish dictionary look at the example program spanish py and run it """ tiny english to spanish dictionary is createdusing the python dictionary type dict then the dictionary is usedbriefly "" beginning with python |
10,356 | spanish dict(spanish['hello''holaspanish['yes''sispanish['one''unospanish['two''dosspanish['three''tresspanish['red''rojospanish['black''negrospanish['green''verdespanish['blue''azulprint(spanish['two']print(spanish['red']first an empty dictionary is created using dict()and it is assigned the descriptive name spanish to refer to the definition for wordyou use the dictionary namefollow it by the word inside square brackets this notation can either be used on the left-hand side of an assignment to make (or remakea definitionor it can be used in an expression (as in the print functions)where its earlier definition is retrieved for examplespanish['hello''holamakes an entry in our spanish dictionary for 'hellowith definition 'holaprint(spanish['red']retrieves the definition for 'red'which is 'rojosince the spanish dictionary is defined at the top-levelthe variable name spanish is still defined after the program runsafter running the programuse spanish in the shell to check out the translations of some more wordsother than 'twoand 'redcreating the dictionary is well defined and quite different activity from the use of the dictionary at the end of the codeso we can use functions to encapsulate the task of creating the dictionaryas in the example program spanish pywhich gives the same result""" tiny english to spanish dictionary is createdusing the python dictionary type dict then the dictionary is usedbriefly ""def createdictionary()'''returns tiny spanish dictionary''spanish dict(spanish['hello''holaspanish['yes''sispanish['one''unospanish['two''dosspanish['three''tresspanish['red''rojospanish['black''negrospanish['green''verdespanish['blue''azulreturn spanish def main()dictionary createdictionary(print(dictionary['two']print(dictionary['red'] dictionaries |
10,357 | main(this code illustrates several things about functions firstlike whole filesfunctions can have documentation string immediately after the definition heading it is good idea to document the return valuethe dictionary that is created is returnedbut the local variable name in the functionspanishis lost when the function terminates to remember the dictionary returned to mainit needs name the name does not have to match the name used in createdictionary the name dictionary is descriptive we could also use the dictionary more extensively the example program spanish py is the same as above except it has the following main methoddef main()dictionary createdictionary(print('count in spanishdictionary['one''dictionary['two''+dictionary['three'''print('spanish colorsdictionary['red''dictionary['blue''+dictionary['green'''try itand check that it makes sense python dictionaries are actually more general than the common use of dictionaries they do not have to associate words and their string definitions they can associate many types of objects with some arbitrary object the more general python terminology for word and definition are key and value given keyyou can look up the corresponding value the only restriction on the key is that it be an immutable type this means that value of the key' type cannot be changed internally after it is initially created strings and numbers are immutable dictionary is mutableits value can be changed internally (you can add new definitions to it!we will see more mutable and immutable types later and explore more of the internal workings of data types number dictionary exercise write tiny python program numdict py that makes dictionary whose keys are the words 'one''two''three'and 'four'and whose corresponding values are the numerical equivalents and (of type intnot stringsinclude code to test the resulting dictionary by referencing several of the definitions and printing the results (this dictionary illustrates simply that the values in python dictionary are not required to be strings dictionaries and string formatting at the end of the main function in spanish py from the last sectiontwo strings are constructed and printed the expressions for the two strings include sequence of literal strings concatenated with interspersed values from dictionary there is much neatermore readable way to generate these strings we will develop this in several steps the first string could be constructed and printed as followsnumberformat 'count in spanish{one}{two}{three}withsubstitutions numberformat format(one='uno'two='dos'three='tres'print(withsubstitutionsthere are several new ideas herewe are using an alternate form of format string and format method parameters from those described in string format operation (page beginning with python |
10,358 | note the form of the string assigned the name numberformatit has the english words for numbers in braces where we want the spanish definitions substituted (this is unlike in string format operation (page )where we had empty braces or numerical index inside as in string format operation (page )the second line uses method calling syntax reminder of the syntax for methodsobject methodname(parametershas the object followed by period followed by the method nameand further parameters in parentheses in the example abovethe object is the string called numberformat the method is named format the parameters in this case are all keyword parameters you have already seen keyword parameter sep used in print function calls in this particular applicationthe keywords are chosen to include all the words that appear enclosed in braces in the numberformat string when the string numberformat has the format method applied to it with the given keyword parametersa new string is created with substitutions into the places enclosed in braces the substitutions are just the values given by the keyword parameters hence the printed result is count in spanishunodostresnow we go one step furtherthe keyword parameters associate the keyword names with the values after the equal signs the dictionary from spanish py includes exactly the same associations there is special notation allowing such dictionary to supply keyword parameters assuming dictionary is the spanish dictionary from spanish pythe method call numberformat format(one='uno'two='dos'three='tres'returns the same string as numberformat format(**dictionarythe special syntax *before the dictionary indicates that the dictionary is not to be treated as single actual parameter instead keyword arguments for all the entries in the dictionary effectively appear in its place below is substitute for the main method in spanish py the whole revised program is in example program spanish pydef main()dictionary createdictionary(numberformat "count in spanish{one}{two}{three}withsubstitutions numberformat format(**dictionaryprint(withsubstitutionsprint("spanish colors{red}{blue}{green}format(**dictionary)in this main function the string with the numbers is constructed in steps as discussed above the printing of the string with the spanish colors is coded more concisely there are not named variables for the format string or the resulting formatted string you are free to use either coding approach in generaluse this syntax for the string format method with dictionaryreturning new formatted stringformatstring format(**adictionarywhere the format string contains dictionary keys in braces where you want the dictionary values substituted the dictionary key names must follow the rules for legal identifiers at this point we have discussed in some detail everything that went into the first sample programmadlib pyin sample programexplained (page )this is certainly the most substantial program so far dictionaries |
10,359 | look at madlib py againsee how we have used most of the ideas so far if you want more descriptionyou might look at section sample programexplained (page again (or for the first time)it should make much more sense now we will use madlib py as basis for more substantial modifications in structure in the revised mad lib program (page mad lib exercise to confirm your better understanding of madlib pyload it in the editorrename it as mymadlib pyand modify it to have less lame storywith more and different entries in the dictionary make sure addpick is called for each key in your format string test your version dictionaries and python variables dictionaries are central to the implementation of python each variable identifier is associated with particular value these relationships are stored in dictionaries in pythonand these dictionaries are accessible to the useryou can use the function call locals(to return dictionary containing all the current local variables names as keys and all their values as the corresponding dictionary values this dictionary can be used with the string format methodso you can embed local variable names in format string and use them very easilyfor examplerun the example program arithdict py '''fancier format string examplewith locals('' sum prod formatstr '{ { {sum}{ { {prodequations formatstr format(**locals()print(equationsnote the variable names inside braces in formatstrand the dictionary reference used as the format parameter is **locals( string like formatstr is probably the most readable way to code the creation of string from collection of literal strings and program values the ending part of the syntaxformat(**locals())may appear bit strangebut it is very usefulit clearly indicate how values are embedded into the format stringand avoids having long list of parameters to format the example program hello_you py does the same thing as the earlier hello_you versionsbut with dictionary reference'''hello to you''illustrates locals(for formating in print person input('enter your name'greeting 'hello{person}!format(**locals()print(greetingf-strings(optionalbut handy! simplification for formatting added in python is -strings they have many featuresbut the simplest thing is to shorten formatting of literal string with local variable references like abovemerely add an immediately before the literal format stringand eliminate the format(**locals()see example arithfstring py beginning with python |
10,360 | '''fancier -string example for formatting'' sum prod print( '{ { {sum}{ { {prod'see the directly before the literal format string automatically substituting local variable values quotient string dictionary exercise create quotientdict py by modifying quotientreturn py in quotient string return exercise (page so that the quotientstring function accomplishes the same thingput local variable names inside the braces of format stringand either process the format string by appending format(**locals()or else make the format string into an -string if you use meaningful names for the variablesthe format string should be particularly easy to understand loops and sequences modern computers can do millions or even billions of instructions second with the techniques discussed so farit would be hard to get program that would run by itself for more than fraction of second practicallywe cannot write millions of instructions to keep the computer busy to keep computer doing useful work we need repetitionlooping back over the same block of code again and again there are two python statement types to do thatthe simpler for loopswhich we take up shortlyand while loopswhich we take up laterin while statements (page two preliminaries the value of already defined variables can be updated this will be particularly important in loops to prepare for that we first follow how variables can be updated in an even simpler situationwhere statements are just executed in textual order sequence types are used in for loops we will look at basic sequence typelist then we put this all together this is long section go slowly and carefully updating variables the programs so far have defined and used variablesbut other than in early shell examples we have not changed the value of existing variables for now consider particularly simple examplejust chosen as an illustrationin the example file updatevar py simple sequential code updating two variables * print(xycan you predict the resultrun the program and check particularly if you did not guess rightit is important to understand what happensone step at time that means keeping track of what changes to variables are made by each statement in the table belowstatements are referred to by the numbers labeling the lines in the code above we can track the state of each variable after each line is executed dash is shown where variable is not defined for instance after loops and sequences |
10,361 | line is executeda value is given to xbut is still undefined then gets value in line the comment on the right summarizes what is happening since has the value when line startsx+ is the same as + in line three we use the fact that the right side of an assignment statement uses the values of variables when the line starts executing (what is left after the previous line of the table executed)but the assignment to the variable on the left causes change to yand hence the updated value of is shown in the table line then changes xusing the latest value of ( not the initial value !the result from line confirms the values of and line comment = + using the value of from the previous line = * on the rightuse the value of from the previous line = - on the rightuse the value of and from the previous line print when we create such tablethe order of execution will always be the order of the lines in the table in this simple sequential codethat also follows the textual order of the program following each line of execution of program in the proper order of executioncarefullykeeping track of the current values of variableswill be called playing computer table like the one above is an organized way to keep track the list type lists are ordered sequences of arbitrary data lists are the first kind of data discussed so far that are mutablethe length of the sequence can be changed and elements substituted we will delay the discussion of changes to lists until further introduction to objects lists can be written explicitly read the following examples ['red''green''blue'[ ['silly' 'mixed'- 'example'[the empty list [ ][ ][list containing three elementseach list the basic format is square-bracket-enclosedcomma-separated list of arbitrary data the range functionpart there is built-in function rangethat can be used to automatically generate regular arithmetic sequences try the following in the shelllist(range( )list(range( )the general pattern for use is range(sizeofsequencethis syntax will generate the integersone at timeas needed if you want to see all the results at once as listyou can convert to list as in the examples above the resulting sequence starts at and ends before the parameter we will see there are good reasons to start from in python one important property of sequences generated by range(nis that the total number of elements is nthe sequence omits the number itselfbut includes instead with more parametersthe range function can be used to generate much wider variety of sequences the elaborations are discussed in random colors (page and the most general range function (page in computer jargonproducing values of sequence only as needed is called lazy evaluation beginning with python |
10,362 | basic for loops try the following in the shell you get sequence of continuation lines before the shell responds after seeing the colon at the end of the first linethe shell knows later lines are to be indented be sure to enter another empty line (just press enter at the end to get the shell to respond for count in [ ]print(countprint('yescountthis is for loop it has the heading starting with forfollowed by variable name (count in this case)the word insome sequenceand final colon as with function definitions and other heading linesthe colon at the end of the line indicates that consistently indented block of statements follows to complete the for loop for item in sequenceindented statements to repeatmay use item the block of lines is repeated once for each element of the sequenceso in this example the two lines in the indented block are repeated three times furthermore the variable in the heading (count heremay be used in the blockand each time through it takes on the next value in the sequenceso the first time through the loop count is then and finally look again at the output and see that it matches this sequence more detailed sequence is givenplaying computerin the tableline count comment start with the first element of the list print 'yes is 'yes'print yes change count to the next element in the list print 'yes is 'yesyes'print yesyeschange count to the next element in the list print 'yes is 'yesyesyes'print yesyesyesdone with list when executing step by stepnote that the for loop heading serves two purposeseach time the heading line executesit implicitly assigns new value to the variable name you use in place of item after each execution of the heading linethe statements in the indented block are executedgenerally making use of the the new value for the variable assigned in the heading notewhen playing computer with loopthe same line numbers can reappear over and overbecause the for loop heading line and the indented body under it are each executed repeatedly each time one of these lines is executedit must be listed separatelyin time sequencea for loop is technically single compound statement its level of indentation is considered to be the level of indentation of its heading when you used the shell to enter loopthere was reason that the interpreter waited to respond until after you entered an empty linethe interpreter did not know how long the loop block was going to bethe empty line is signal to the interpreter that you are done with the loop blockand hence ready to execute the complete compound loop statement look at the following example program for pyand run it loops and sequences |
10,363 | for count in [ ]print(countprint('yescountprint('done counting 'for color in ['red''blue''green']print(colorin filewhere the interpreter does not need to respond immediatelythe blank line is not necessary insteadas with function definition or any other format with an indented blockyou indicate being past the indented block by dedenting here the following print statement has the same level of indentation as the for loop heading because they have the same level of indentationthey are executed in sequence hence in the code above"done counting is printed once after the first loop completes all of its repetitions execution of the program ends with another simple loop as with the indented block in functionit is important to get the indentation right alter the code aboveso the fourth line is indentedfor count in [ ]print(countprint('yescountprint('done counting 'changed so indented for color in ['red''blue''green']print(colorpredict the changeand run the code again to test loops are one of the most important features in programming while the for loop syntax is pretty simpleusing them creatively to solve problems (rather than just look at demonstrationis among the biggest challenges for many learners at an introductory level one way to simplify the learning curve is to classify common situations and patternsand give them names one of the simplest patterns is illustrated in all of the for loop examples so fara simple foreach loopfor each element of the sequencedo the same sort of thing with it stated as more pythonic pseudo-codefor item in sequencedo something with the current item (it would be even more like english if for were replace by for eachbut the shorter version is the one used by python in the for loop examples abovesomething is printed that is related to each item in the list printing is certainly one form of "do something"but the possibilities for "do somethingare completely generalwe can use for-each loop to revise our first example in the tutorial recall the code from madlib pyaddpick('animal'userpicksaddpick('food'userpicksaddpick('city'userpickseach line is doing exactly the same thingexcept varying the string used as the cuewhile repeating the rest of the line this is the for-each patternbut we need to list the sequence that the cues come from read the alternativefor cue in ['animal''food''city']addpick(cueuserpicksheading body seeing this feature requires the ability to abstract the general pattern from the group of examples this is essential for using loops effectively beginning with python |
10,364 | if you wish to see or run the whole program with this small modificationsee the example madlibloop py common naming convention is used in the programeach element in the list is cuewhile the list with all the elements is named with the plural cues in later situations make list name be the plural of the variable name used for an individual item of the list note the logic of the transformation between the two program versionsthe alternative pieces of data are collected in the list in the for loop heading single variable name (here chose cueis used in the heading as placeholder to refer to the current choice being handledand the body refers to this variable cue in place of the explicit data values included each time in the original no-loop version it is important to understand the sequence of operationshow execution goes back and forth between the heading and the body here are the details heading first timevariable cue is set to the first element of the sequence'animal body first timesince cue is now 'animal'effectively execute addpick('animal'userpicks(skip the details of the function call in this outline heading second timevariable cue is set to the next element of the sequence'food body second timesince cue is now 'food'effectively execute addpick('food'userpicks heading third timevariable cue is set to the next (lastelement of the sequence'city body third timesince cue is now 'city'effectively execute addpick('city'userpicks heading donesince there are no more elements in the sequencethe entire for loop is done and execution would continue with the statement after it (not indentedin this example the data values are just few given literalsand there is only one line in the repeated pattern hence the use of for loop is not big dealbut it makes simple examplethis looping construction would be much handier if you were to modify the original mad lib exampleand had story with many more cues also this revision will allow for further improvements in the revised mad lib program (page )after we introduce more about string manipulation pattern loop exercise write two-line for-each loop in file types py containing call to the type functionso that this code with the for-each loop produces exactly the same printed output as the code in example file types py the types py code is shown belowprint( type( )print( type( )print([]type([])print(truetype(true)print(nonetype(none)execute both versions to check yourself hint hint triple exercise complete the following function this starting code is in triplestub py save it to the new name triple py note the way an example is given in the documentation string it simulates the use of the function in the shell this is common convention the elements of the list in the for loop heading are not all of the same type you need to use the loop variable twice in the loop body loops and sequences |
10,365 | def tripleall(nums)''print triple each of the numbers in the list nums tripleall([ ] tripleall([- ]- ''simple repeat loop the examples above all used the value of the variable in the for loop heading an even simpler for loop usage is when you just want to repeat the exact same thing specific number of times in that case only the length of the sequencenot the individual elements are important we have already seen that the range function provides an easy way to produce sequence with specified number of elements read and run the example program repeat py'' simple repeat loop''for in range( )print('hello'in this situationthe variable is not used inside the body of the for-loop the user could choose the number of times to repeat read and run the example program repeat py'''the number of repetitions is specified by the user '' int(input('enter the number of times to repeat')for in range( )print('this is repetitious!'when you are reading codeyou look at variable names as they are introducedand see where they are used later in the simple repeat loops abovethe loop variable is introducedbecause there must be variable name therebut it is never used one convention to indicate the simple repeat loop variable is never used againis to use the special variable name (just an underscore)as infor in range( )print('hello'successive modification loops suppose have list of items called itemsand want to print out each item and number them successively for instance if items is ['red''orange''yellow''green'] would like to see the output red orange yellow green read about the following thought process for developing thisif allow myself to omit the numbersit is easyfor any item in the listi can process it with beginning with python |
10,366 | print(itemand just go through the list and do it for each one (copy and run if you like items ['red''orange''yellow''green'for item in itemsprint(itemclearly the more elaborate version with numbers has pattern with some consistencyeach line is at least in the formnumber item but the number changes each timeand the numbers do not come straight from the list of items variable can changeso it makes sense to have variable numberso we have the potential to make it change correctly we could easily get it right the first timeand then repeat the same number read and run the example program numberentries py'''in this version number does not change ''items ['red''orange''yellow''green'number for item in itemsprint(numberitemof course this is still not completely correctsince the idea was to count after the first time number is printedit needs to be changed to to be right the next time through the loopas in the following coderead and run the example program numberentries py'''prints poorly numbered entries from the list''items ['red''orange''yellow''green'number for item in itemsprint(numberitemnumber will change to after printing this is closerbut still not completely correctsince we never get to we need way to change the value of number that will work each time through the loop the pattern of counting is simpleso simple in fact that you probably do not think consciously about how you go from one number to the nextyou can describe the pattern by saying each successive number is one more than the previous number we need to be able to change number so it is one more than it was before that is the additional idea we needchange the last line of the loop body to get the example program numberentries py see the addition and run it items ['red''orange''yellow''green'number for item in itemsprint numbered entries print(numberitemnumber number crucial added line it is important to understand the step-by-step changes during execution below is another table showing the results of playing computer the line numbers are much more important here to keep track of the flow of controlbecause of the jumping around at the end of the loop again note that the program line numbers in the line column of the playing computer table are not all listed sequentiallybecause the for loop heading line and the indented body under it are each executed repeatedly for compactnessthe variable items does not get its own columnsince it always has the value shown in the comment in line loops and sequences |
10,367 | line item 'red'red'red'orange'orange'orange'yellow'yellow'yellow'green'green'green'greennumber comment set items to ['red''orange','yellow''green'start with item as first in sequence print red + on to the next element in sequence print orange = + on to the next element in sequence print yellow = + on to the last element in sequence print green = + sequence doneend loop and code the final value of number is never usedbut that is ok what we want gets printed go through carefully and be sure you understand the meaning of each entry in the tableand the reason for the sequencing and the reason for the exact position of each entry in each step where it changesin particular see how and why the line number for each successive row is not always one more than the previous row in particularsee how the same sequence of numbered lines may be repeated in multiple places in the table without this understanding you will not be able to play computer yourself and really understand loops this short example illustrates lot of ideas important to loopsloops may contain several variables one way variable can change is by being the variable in for loop headingthat automatically goes through the values in the for loop list another way to have variables change in loop is to have an explicit statement that changes the variable inside the loopcausing successive modifications there is general pattern to loops with successive modification of variable like number above the variables to be modified need initial values before the loop (line in the example above the loop heading causes the repetition in for-loopthe number of repetitions is the same as the size of the list the body of the loop generally "does something(like print above in line that you want done repeatedly there is code inside the body of the loop to set up for the next time through the loopwhere the variable which needs to change gets transformed to its next value (line in the example abovethis information can be put in code outlineinitialize variables to be modified loop heading controlling the repetitiondo the desired action with the current variables modify variables to be ready for the action the next time if you compare this pattern to the for-each and simple repeat loops in basic for loops (page )you see that the examples there were simpler there was no explicit variable modification needed to prepare for the next time though the loop we will refer to the latestmore general pattern as successive modification loop beginning with python |
10,368 | functions are handy for encapsulating an idea for use and reuse in programand also for testing we can write function to number listand easily test it with different data read and run the example program numberentries py''use function to number the entries in any list''def numberlist(items)'''print each item in list itemsnumbered in order ''number for item in itemsprint(numberitemnumber number def main()numberlist(['red''orange''yellow''green']print(numberlist(['apples''pears''bananas']main(make sure you can follow the whole sequencestep by stepthis program has the most complicated flow of control so farchanging both for function calls and loops execution start with the very last linesince the previous lines are definitions then main starts executing the first call to numberlist effectively sets the formal parameter items ['red''orange''yellow''green'and the function executes just like the flow followed in numberentries py this timehoweverexecution returns to main an empty line is printed in the second line of main the second call to numberlist has different actual parameter ['apples''pears''bananas']so this effectively sets the formal parameter this time items ['apples''pears''bananas'and the function executes in similar pattern as in numberentries pybut with different data and one less time through the loop execution returns to mainbut there is nothing more to do accumulation loops suppose you want to add up all the numbers in listnums let us plan this as function from the beginningso read the code below we can start withdef sumlist(nums)'''return the sum of the numbers in nums ''if you do not see what to do right awaya useful thing to do is write down concrete caseand think how you would solve itin complete detail if nums is [ ]you would likely calculate is is is is the answer to be returned loops and sequences |
10,369 | since the list may be arbitrarily longyou need loop hence you must find pattern so that you can keep reusing the same statements in the loop obviously you are using each number in the sequence in order you also generate sum in each stepwhich you reuse in the next step the pattern is differenthoweverin the first line + is there is no previous sumand you use two elements from the list the is not added to previous sum although it is not the shortest way to do the calculation by hand is sum of we can make the pattern consistent and calculatestart with sum of is is is is is the answer then the second part of each sum is number from the listnums if we call the number from the list numthe main calculation line in the loop could be nextsum sum num the trick is to use the same line of code the next time through the loop that means what was nextsum in one pass becomes the sum in the next pass one way to handle that issum for num in numsnextsum sum num sum nextsum do you see the patternagain it is initialization loop headingmain work to be repeated preparation for the next time through the loop sometimes the two general loop steps can be combined this is such case since nextsum is only used oncewe can just substitute its value (sumwhere it is used and simplify tosum for num in numssum sum num so the whole functionwith the return statement is def sumlist(nums)'''return the sum of the numbers in the list nums ''sum for num in numssum sum num return sum the example program sumnums py has the code above with the following line added at the end to test the function (not indentedrun sumnums py print(sumlist([ ])the pattern used here is certainly successive modification (of the sum variableit is useful to give more specialized name for this version of the pattern here it follows an accumulation pattern beginning with python |
10,370 | initialize the accumulation to include none of the sequence (sum herefor item in sequence new value of accumulation result of combining item with last value of accumulation this pattern will work in many other situations besides adding numbers english loop terminologyof course you need to be able to go from an english description of problem to plan and then implement it in python in particularit will be very important to realize when you will need your program to have loop through sequence what are some common words or phrases that suggest loopafter thinking for yourselfcompare once you see this need for loopyou need to plan your code there are bunch of questions you can routinely ask yourself about fleshing out the outline for the loop part of your codeinitialization loop headingmain work to be repeated preparation for the next time through the loop what is the sequencewhat descriptive name can give to the loop variable write the for loop heading with this decidedyou no longer need to think about the whole program at onceyou can focus on what you do for one elementwith the name you gave in the loop heading what do need to do for single element of the sequencedoes this involve other variablesif sohow will initialize themwrite this action into the body of the loopusing the loop variable does the main action involve variableother than the loop variablethat needs to change each time through the loopif sohow do relate the present and next valuesand change the value to be ready for the next time through the loopwriting the sequence for specific example may help finallycode this update play computer sumlist exercise suppose the function sumlistdefined aboveis called with the parameter [ play computer on this callusing the file playcomputersumstub rtfopened from an operating system window for the examples directory do not open in idle the file should come up in your usual word processor immediately save the file as playcomputersum rtfand fill in blank cells in the table make sure there is row in the table for each line executed in the programwith separate line entry for each time line is executed in each row enter which program line is being executedand show all changes caused to variables by the execution of that one line display line numbers as shown in the margin beside the example code in the tutorial (the separate python files themselves do not show the line numbers table is started for you below the final row that you enter in your your table should be for an execution of line numbered in the codeand your comment can be"return if the same variable value in one column repeats through several rowsit is more convenient just leave the later entries blankrather than keep copying with this conventionthe current value of variable is the last value recorded in previous line in the table this is the first "play computerexercise with loop be sure to look back at the earlier play computer examples the lines in the loop (and hence their line numbersrepeat multiple times as rows in the tableas you follow the loop one time through after anotherthe original parameterwhich does not changedoes not have column in the tablefor compactness the start of the table is shown below as shown in the first commentthroughout the function callnums is "do each""do every""for all""process each""do ___ times" loops and sequences |
10,371 | [ line sum num comment set nums to [ ]skip line doc string test sumlist exercise write program testsumlist py which includes main function to test the sumlist function several times include test for the extreme casewith an empty list join all exercise complete the following function this starting code is in joinallstub py save it to the new name joinall py note the way an example is given in the documentation string it simulates the use of the function in the shell this is common conventiondef joinstrings(stringlist)'''join all the strings in stringlist into one stringand return the resultnot printing it for examples joinstrings(['very''hot''day']returns string print(sveryhotday ''first hint second hint more playing computer testing code by running it is finebut looking at the results does not mean you really understand what is going onparticularly if there is an errorpeople who do not understand what is happening are likely to make random changes to their code in an attempt to fix errors this is very badincreasingly self-defeating practicesince you are likely to never learn where the real problem liesand the same problem is likely to come back to bite you it is important to be able to predict accurately what code will do we have illustrated playing computer on variety of small chunks of code playing computer can help you find bugs (errors in your codesome errors are syntax errors caught by the interpreter in translation some errors are only caught by the interpreter during executionlike failing to have value for variable you use other errors are not caught by the interpreter at all you just get the wrong answer these are called logical errors earlier logical errors can also trigger an execution error later this is when playing computer is particularly useful common error in trying to write the numberlist function would be to have the following code (extracted from numberentrieswrong py) def numberlist(items)#wrong code for illustration '''print each item in list itemsnumbered in order ''for item in itemsnumber print(numberitemnumber number this is form of accumulationbut not quite the same as adding numbers "start with nothing accumulateddoes not mean here you are dealing with stringsnot numbers think what is appropriate beginning with python |
10,372 | you can run this code and see that it produces the wrong answer if you play computer on the call to numberlist(['apples''pears''bananas'])you can see the problemline item 'apples'apples'apples'apples'pears'pears'pearsnumber comment set items to ['apples''pears''bananas'start with item as first in sequence print apples + on to the next element in sequence print pears oopsif you go step by step you should see where the incorrect came fromthe initialization is repeated each time in the loop at line undoing the incrementing of number in line messing up your count warningalways be careful that your one-time initialization for loop goes before the loopnot in itfunctions can also return values consider the python for this mathematical sequencedefine the function ( xlet find (ym( - ) def ( )mathematical function return * print( (ym( * - )this code is in example mathfunc py similar example was considered in returned function values (page )but now add the idea of playing computer and recording the sequence in table like when you simplify mathematical expressionpython must complete the innermost parts first tracking the changes means following the function calls carefully and using the values returned again dash '-is used in the table to indicate an undefined variable not only are local variables like formal parameters undefined before they are first usedthey are also undefined after the termination of the functionline - comment remember definition of start onprint( (ym( * - ))first want ( )which is ( pass to function mso = return * substitute resultprint( ( * - ))want ( * - )which is ( * - ( pass to function mso = return * substitute resultprint( )so calculate and print thus far most of the code given has been motivated firstso you are likely to have an idea what to expect you may need to read code written by someone else (or even yourself while back!where you are not sure what is intended also you might make mistake and accidental write code that does something unintendedif you really understand how python worksone line at timeyou should be able to play computer and follow at least short code sequences that have not been explained before it is useful to read another person' code and try to follow it the next exercises also provides code that has not been explained firstor has mistake loops and sequences |
10,373 | play computer odd loop exercise work in word processor (not idle!)starting from example playcomputerstub rtfand save the file as playcomputer rtf the file has tables set up for this and the following two exercise play computer on the following code exercise play computer loop for in [ ] * print(xreality check is printed when line finally executes the start of the table for this exercise is shown below line comment play computer error exercise in word processor add to the file playcomputer rtfstarted in the previous exercise the following code is supposed to compute the product of the numbers in list for instance product([ ]should calculate and return * * = in stepscalculating * = and * = def product(nums)for in numsprod prod prod* return prod #play computer error exercise the code for this exercise appears in the example file numproductwrong py major use of playing computer is to see exactly where the data that you expect gets messed up play computer on call to product([ ]until you see that it makes mistakeand produces wrong number then you can stop extending the tablejust ending with comment about how the error is now visible the table headings and the first row of the table for this exercise are shown below line prod comment set nums to [ then you can stop and fix itfirst copy numproductwrong py to numproduct pyand fix the new file (and save again!play computer functions exercise in word processor once again add to the file playcomputer rtfstarted in the previous exercises play computer on the following code def ( )#play computer functions exercise return + print( ( )* ( ) beginning with python |
10,374 | reality check is printed the table headings and the first row of the table for this exercise are shown below line - comment remember definition you will revisit line several timeswith table lines for function execution interspersed look at the example above which has table showing function returning value twicethe print function keyword end by default the print function adds newline to the end of the string being printed this can be overridden by including the keyword parameter end the keyword end can be set equal to any string the most common replacements are the empty string or single blank if you also use the keyword parameter septhese keyword parameters may be in either orderbut keyword parameters must come at the end of the parameter list read the illustrationsprint('all''on''same''line'print('different line'is equivalent to print('all''onend='print('same'end='print('line'print('different line'this does not work directly in the shell (where you are always forced to new line at the endit does work in programbut it is not very useful except in loopsuppose want to print line with all the elements of listseparated by spacesbut not on separate lines can use the end keyword set to space in the loop can you figure out in your head what this example file endspace py doesthen try itdef listononeline(items)for item in itemsprint(itemend='listononeline(['apple''banana''pear']print('this may not be what you expected!'if you still want to go on to new line at the end of the loopyou must include print function that does advance to the next lineonceafter the loop try this variationendspace py def listononeline(items)for item in itemsprint(itemend='print(listononeline(['apple''banana''pear']print('this is probably better!' decimalsfloatsand floating point arithmetic floating point numbers like are basic typebut there are some complications due to their inexactness this section may be deferred until you actually need numbers other than integers decimalsfloatsand floating point arithmetic |
10,375 | floatsdivisionmixed types as you moved on in school from your first integer division to fractions and decimalsyou probably thought of / as fraction and could convert to decimal python can do decimal calculationstooapproximately try all set-off lines in this section in the shell / / there is more going on here than meets the eye as you should knowdecimal representations of values can be pain they may not be able to be expressed with finite number of characters try / alsoas you may have had emphasized in science classreal number measurements are often not exactand so the results of calculations with them are not exact in fact there are an infinite number of real number just between and and computer is finite it cannot store all those numbers exactlyon the other handpython does store integers exactly (well at least far past the number of atoms in the universe eventually even integers could get too big to store in computerthe difference in the way integers and decimals are stored and processed leads to decimals and integers being different types in python try type( note that is of type 'float'not 'decimalthere are several reasons for that name having to do with the actual way the type is stored internally "decimalimplies base tenour normal way for writing numbers with ten digits , , , , , , , , , computers actually use base twowith only two symbols , (did you note what symbols were in the machine language in context (page )?also floats use an encoding something like scientific notation from science classwith exponents that allow the decimal point to move or "float"as in the decimal case ( ) try type(- type(- even number that is actually an integer can be represented in the float type if decimal point is included always be sure to remember that floats may not be exact the use of base two makes this true even in cases where decimal numbers can be expressed exactlymore on that in string formats for float precision (page it is sometimes important to know the numeric type of the result of binary operation any combination of +-and with operands of type int produces an int if there is an operation /or if either operand is of type floatthe result is float try each in the shell (and guess the resulting type) * exponentiationsquare roots exponentiation is finding powers in mathematical notation( )( )( )( )= in python there is no fancy typography with raised exponent symbols like the so python uses *before powertry in the shell python does what you would expect mathematically with an expression like ( / * cautionthis is not the case in other common languages like java and +(or with python they treat the operation with integers like the current python //so the result of the expression above is since // is beginning with python |
10,376 | ** * ** if you expected for the second expressionremember exponentiation has even higher precedence than multiplication and division ** is * * or and * is exponents do not need to be integers useful example is the powerit produces square root try in the shell * * the result of power operation is of int type only if both parameters are integers and the correct result is an integer string formats for float precision you generally do not want to display floating point result of calculation in its raw formoften with an enormous number of digits after the decimal pointlike you are likely to prefer rounding it to something like there are two approaches first there is format function (not methodwith second parameter allowed to specialize the formatting of objects as strings read the following example interpreter sequence showing possibilities when float is being formattedx format( ' ' format( '' note that the results are rounded not truncatedthe result to two places is not the formatting string fmeans round to places after the decimal point similarly fmeans round to two decimal places warningthis format function returns the formatted string it does not change the parameters as complete statement in program format( ')is uselessthe ' gets returned and thrown awaywith no effect on the first versionsaving the formatted value to swill allow the formatted string to be used again (as sthis rounding notation can also be placed after colon inside the braces of format stringsfor use with the string format method you can put colon and the formatting information we used in the simple format method above (like but with no quotesrecall there are many ways to indicate what values to substitute into format string the first way introduced is just to omit any reference to the variables and substitute the method' parameters in order as inx ' long{ } short{ } { fformat(xxy' long short the first part inside the formatting braces can also indicate what value to substituteas when using dictionary 'long{ }short{ fformat(**locals()'long short decimalsfloatsand floating point arithmetic |
10,377 | the instructions for the data to insert can also be given by position index (from the optional end of string format operation (page )) 'longer{ }shorter{ fformat( 'longer shorter in each of these approachesthe colon and formatting specification come at the end of the expression inside the bracesjust before the closing this follows the and symbols (if anyidentifying what value to use for the substitution there are many more fancy formatting options for the string format method that we will not discuss going to the opposite extremeand using formatting with many digitsyou can check that python does not necessarily remember simple decimal numbers exactlyformat '' format '' format '' format '' python stores the numbers correctly to about or digits you may not care about such slight errorsbut you will be able to check in that if python tests the expressions and for equalityit decides that they are not equalin factas you can see abovethe approximations that python stores for the two expressions are not exactly equal warningdo not depend on the exactness of floating point arithmeticeven for apparently simple expressionsfloating point formatting code similar to this section is also in example program floatformat py floating point exercise write programdiscount pythat prompts the user for an original price and for discount percentage and prints out the new price to the nearest cent for example if the user enters for the price and for the discount percentagethe value would be ( / rounded to two decimal places for price with percent discountthe value would be ( / rounded to two decimal places write the general calculation code following the pattern of the calculations illustrated in the two concrete examples summary section references in square brackets indicate where an idea was first discussed where python syntax is illustratedthe typeface continues to indicate the category of each part in python +the previous expressions make sensebut in earlier versions of python and in other languages like +and javawhere there are not separate division operators /and /these expressions would be wrong because of the multiple meanings of the operator with different types the expressions would work in these other languages iffor example were replaced by beginning with python |
10,378 | typeface typewriter font emphasized bold normal text meaning text to be written verbatim place where you can use an arbitrary expression place where you can use an arbitrary identifier description of what goes in that positionwithout giving explicit syntax if there are several variations on particular part of the syntaxalternatives will be show on successive lines to emphasize the successive parts of the syntaxspace will generally be left around symbol and punctuation charactersbut the space is not required in actual use python shell (aa shell window may be opened in idle run python shell [windows in idle (page )(bentering commandsi commands may be entered at the prompt [addition and subtraction (page )ii if the shell detects that command is not finished at the end of the linea continuation line is shown with no [multiplicationparenthesesand precedence (page )iii statements with heading ending in colon followed by an indented blockmust be terminated with an empty line [basic for loops (page )iv the shell evaluates completed command immediatelydisplaying any result other than nonestarting on the next line [addition and subtraction (page ) the shell remembers variable and function names [variables and assignment (page )(can earlier shell line may to copied and edited by clicking anywhere in the previously displayed line and then pressing enter idle editing (astart new window from the file menu by selecting newopen or recent files [loading program in the idle editorand running it (page )(bmake your python file names end with py[literals and identifiers (page ) to run program from an idle editor window(aselect run -run module or press function key the program runs in the shell windowafter resetting the shell so all old names are forgotten [loading program in the idle editorand running it (page ) if the program is expecting keyboard inputthe text cursor should appear at the end of the shell history if you somehow move the cursor elsewhereyou must explicitly move it back [the idle editor and execution (page )ii press ctrl- to stop running program in long or infinite loop iii after program terminatesthe shell remembers function definitions and variable names define outside of any function [ first function definition (page ) errors come in three categories(asyntax errorstext that the interpreter recognizes as illegal when first reading it this prevents execution of your code python lets you know where it realized there was an error sometimes this is the exact locationbut the actual error could be anywhere earlieroften on the previous line [variables and assignment (page )(bexecution errorsthe first illegal action is detected while running your command or program the source of the error could be in the line where execution failsor it could be an earlier logical error that only later forces an execution error [variables and assignment (page )execution errors generate traceback [function parameters (page ) summary |
10,379 | (clogical errorswhen python detects nothing illegalbut you do not get the results you desire these errors are the hardest to trace down playing computer and additional print functions help [more playing computer (page ) type int(short for integer)(aliteral integer values may not contain decimal point [floatsdivisionmixed types (page )(bintegers may be arbitrarily large and are stored exactly [floatsdivisionmixed types (page )(cintegers have normal operationswith usual precedence (highest listed first) **exponentiation ( ** means * * [exponentiationsquare roots (page )ii *///%multiplicationdivision with float resultinteger division (ignoring any remainder)just the remainder from division [division and remainders (page )iii +-additionsubtraction [addition and subtraction (page ) type float(short for floating point)approximations of real numbers (aliteral values must contain decimal point to distinguish them from the int type [floatsdivisionmixed types (page )(bapproximates wide range of values [floatsdivisionmixed types (page )(cdoes not dependably store numbers exactly even numbers with simple decimal representation [floatsdivisionmixed types (page )(dhas the same operation symbols as for integersbut always with float result [floatsdivisionmixed types (page )(ea mixed binary operation with an integer and float produces float result [floatsdivisionmixed types (page ) type str(short for string)literal values contain sequence of characters enclosed in matching quotes (aenclosed in or "the string must be on one line [string delimiterspart (page )(benclosed in ''or """the string may include multiple lines in the source file [triple quoted string literals (page )(cescape codes inside literals include \for single quote and \ for newline [escape codes (page )(dbinary operations (operation symbols have the same precedence order as when the symbols are used in arithmetic[string concatenation (page ) stringexpression stringexpression concatenation (running togetherof the two strings ii stringexpression integerexpression integerexpression stringexpression repeat the string the number of times given by the integer expression (estring format methodi stringformatexpression formatparameter parameter parameter [string format operation (page )where stringformatexpression is any string with an arbitrary number of places for format substitutions in it formatted substitutions are enclosed in braces digit inside the braces will indicate which parameter value is substitutedcounting from if digits are left outthe format parameters are substituted in order the expression inside the braces can end with colon followed by format specifying string such as # where can be non negative beginning with python |
10,380 | integersubstitute numerical value rounded to the specified number of places beyond the decimal point [floatsdivisionmixed types (page )example'word{}int{}formatted float{ fformat('joe' evaluates to'wordjoeint formatted float ii stringformatexpression format*dictionary the format expressions are the same as above except that key name from dictionary appears inside the braces the dictionary referenced appears in the parameter list preceded by *any value to be substituted is then taken from the dictionary by accessing the key exampleif defs is dictionary with defs['name'equaling 'joe'defs['num'equaling defs['dec'equaling then 'word{name}int{num}formatted float{dec fformat(**defsevaluates to the same string as in the previous example (page )[dictionaries and string formatting in particularthe dictionary reference can the the dictionary of all local variable namesby making the parameter to format be **locals([dictionaries and python variables (page )(fstrings are kind of sequence type list expression expression and so on expression [(aa literal list consists of comma separated collection of values all enclosed in square brackets there may be manyoneor no elements in the list [the list type (page )(ba list is kind of sequenceso it may be used as the sequence in for statement heading [basic for loops (page ) type dict (short for dictionarydict(returns an empty dictionary (aa dictionary provides an association of each key to its value the key can be any immutable typewith includes numbers and strings [definition and use of dictionaries (page )(bdictname keyexpression valueexpression associates in the dictionary dictname the key derived from evaluating keyexpression with the value derived from evaluating valueexpression [definition and use of dictionaries (page (cused in an expressiondictname keyexpression summary |
10,381 | evaluates to the value in the dictionary dictname coming from the key obtained by evaluating keyexpression [definition and use of dictionaries (page ) type of nonethis literal value has its own special type none indicates the absence of regular object identifiers (aidentifiers are names for python objects [literals and identifiers (page )(bthey may only contain lettersdigitsand the underscoreand cannot start with digit they are case sensitive [literals and identifiers (page )(cyou cannot use reserved word as an identifiernor are you recommended to redefine an identifier predefined by python in the idle editor you are safe if your identifier names remain colored black [literals and identifiers (page )(dby conventionmulti-word identifiers either [literals and identifiers (page ) use underscores in place of blanks (since blanks are illegal is identifiers)initial_account_balance as in ii use camel-caseall lowercase except for the starting letter of the second and later wordsas in initialaccountbalance variables are identifiers used to name python data [variables and assignment (page )when variable is used in an expressionits latest value is substituted [variables and assignment (page ) statements (aassignment statement[variables and assignment (page )variable expression the expression on the right is evaluatedusing the latest values of all variablesand calculating all operations or functions specified ii the expression value is associated with the variable named on the leftremoving any earlier association with the name (bfor-statement for item in sequence consistently indented statement blockwhich may use the variable item for each element in the sequencerepeat the statement block substituting the next element in the sequence for the variable name item see programming patterns for patterns of use [basic for loops (page )(creturn statement return expression this is used only in function definitioncausing the function to immediately terminate and return the value of expression to the calling codeeffectively acting as if the function call was replaced by this returned value [returned function values (page ) function calls functionname expression expression and so on (athe number of expressions must correspond to number of parameters allowed by the function' definition [function parameters (page ) beginning with python |
10,382 | (beven if there are no parametersthe parentheses must be included to distinguish the name of the function from request to call the function [ first function definition (page )(ceach expression is called an actual parameter each actual parameter is evaluated and the values are passed to the code for the functionwhich executes its defined steps and may return value if the function call was part of larger expressionthe returned value is used to evaluate the larger expression in the place where the function call was [function parameters (page )(dif nothing is returned explicitlythe function returns none (efunction calls may also be used as statementsin which case any value that is returned is ignored (except if entered directly into the shellwhich prints any returned value other than none(fkeyword arguments are special case they have been used optionally at the end of the parameter list for print functions that are built-in (aprint function[print functionpart (page )[the print function keyword end (page )printexpression printexpression expression expression printexpression expression ''sep=strvalend=strval print( print the value of each expression in the list to the standard place for output (usually the screenseparating each value by individual blanks unless the keyword argument sep is specified to change it there can be any number of expressions (not just - as illustratedii the string printed ends with newline unless the keyword argument end is specified to change it iii with no expressionthe statement only advances to new line (ba type name can be used as function to do obvious conversions to the typeas in int(' ')float( )str( [numbers and strings of digits (page )(ctypeexpression return the type of the value of the expression [string delimiterspart (page )(dinputpromptstring print the promptstring to the screenwait for the user to enter line from the keyboardending with enter return the character sequence as string [the input function (page )(elensequence return the number of elements in the sequence [whirlwind introduction to types and functions (page )(frangeexpression require expression to have non negative integer valuecall it generate sequence with length nconsisting of the numbers through - for example range( generates the sequence [the range functionpart (page )(gmaxexpression expression and so on return the maximum of all the expressions listed [whirlwind introduction to types and functions (page ) summary |
10,383 | (hformatexpression formatstring if expression is numericthe format string can be in the form # 'where the gets replaced by nonnegative integerand the result is string with the value of the expression rounded to the specified number of digits beyond the decimal point [floatsdivisionmixed types (page ) functions defined by userdef functionname parameter parameter and so on consistently indented statement blockwhich may include return statement (athere may be any number of parameters the parentheses must be included even if there are no parameters [function parameters (page )(bwhen function is first definedit is only rememberedits lines are not executed [ first function definition (page )(cwhen the function is later called in other codethe actual parameters in the function call are used to initialize the local variables parameter parameter and so on in the same order as the actual parameters [function parameters (page )(dthe local variables of function are independent of the local names of any function defined outside of this function the local variables must be initialized before useand the names lose any association with their values when the function execution terminates [local scope (page )(eif return statement is reachedany further statements in the function are ignored [returned function values (page )(ffunctions should be used toi emphasize that the code corresponds to one idea and give an easily recognizable name [ first function definition (page )ii avoid repetition if basic idea is repeated with just the data changingit will be easier to follow and use if it is coded once as function with parametersthat gets called with the appropriate actual parameters when needed [function parameters (page )iii it is good to separate the internal processing of data from the input and output of data this typically means placing the processing of data and the return of the result in function [function parameters (page )iv separate responsibilitiesthe consumer of function only needs to know the nameparameter usageand meaning of any returned value only the writer of function needs to know the implementation of function [two roleswriter and consumer of functions (page ) modules (program files(aa module may start with documentation string [program documentation string (page )(bdefine your functions in your module if the module is intended as main program called only one waya convention is make your execution just be calling function called main [multiple function definitions (page )(cavoid defining variable outside of your functions names for constant (unchangingvalues are reasonable exception [global constants (page ) documentation stringa stringoften multi-line (triple quotedstring that may appear in two places(aat the very beginning of filethis should give overall introductory information about the file [program documentation string (page ) beginning with python |
10,384 | (bas the very first entry in the body of functionthis should describe[definition and use of dictionaries (page ) the return value of the function (if there is oneii anything about the parameters that is not totally obvious from the names iii anything about the results from the function that is not obvious from the name programming patterns (ainput-calculate-outputthis is the simplest overall program model first obtain all the data you need (for instance by prompting the user for keyboard inputcalculate what you need from this data output the data (for instance to the screen with print functions[the input function (page )(brepetitive patternsthese patterns are all associated with loops loops are essential if the number of repetitions depends on dynamic data in the program even if you could avoid loop by repeating codea loop is usually better choice to make the repetitive logic of your program clear to all exact repetition some number of timesif the number of time to repeat is nfor in rangen )actions to be repeated here the variable is included only because there must be variable name in for loop [simple repeat loop (page )ii for-each loopdo the same sort of thing for each item in specified sequence [basic for loops (page )for item in sequence actions to be done with each item the sequence can be rangewhere item is the next integer in the range iii successive modification looprepeat basic ideabut where the data involved each time changes via pattern that is coded in the loop to convert the previous data into the data needed the next time through the loop [successive modification loops (page )]initialize all variables that will be successively modified in the loop loop heading for the repetition actions to be in each loop with the current variable values modify the variable values to prepare for the next time through the loop iv accumulation loopa sequence of items need to be combined this works where the accumulation of all the items can be approached incrementallycombining one after another with the accumulation so far [accumulation loops (page )]initialize the accumulation to include none of the sequence for item in sequence summary |
10,385 | new value of accumulation partial result where the partial result comes from combining item with the current value of accumulation playing computerfollowing code line by line of execution this either tests that you understand your code (and it works rightor it helps you find where it goes wrong [updating variables (page )successive modification loops (page )more playing computer (page )(amake sure line numbers are labeled (bmake table with heading for line numbersall variables that might be changingand comments (cfollow the order of executionone statement at timebeing careful to update variable values and only use the latest variable valuesand carefully following the flow of control through loops and into and out of function calls with loops and user function callsthe order is not just textual sequential order beginning with python |
10,386 | two objects and methods stringspart iii object orientation python is an object-oriented language every piece of data and even functions and types are objects the term objectoriented is used to distinguish python from earlier languagesclassified as procedural languageswhere types of data and the operations on them were not connected in the language the functions we have used so far follow the older procedural programming syntax in the newer paradigm of object-oriented programmingall data are in objectsand core group of operations that can be done on some particular type of object are tightly bound to the object and called the object' methods for examplestrings are objectsand strings "know howto produce an uppercase version of themselves try in the shells 'hello! upper(here upper is method associated with strings this means upper is function that is bound to the string before the dot this function is bound both logicallyand as we see in the new notationalso syntactically one way to think about it is that each type of data knows operations (methodsthat can be applied to it the expression upper(calls the method upper that is bound to the string and returns new uppercase string result based on strings are immutableso no string method can change the original stringit can only return new string confirm this by entering each line individually in the shell to see the original is unchangeds upper( we are using the new object syntaxobject methodmeaning that the method associated with the object' type is applied to the object this is just special syntax for function call with an object another string method is loweranalogous to upperbut producing lowercase result test yourself how would you write the expression to produce lowercase version of the string sanswer try it in the shell lower( |
10,387 | test yourself in the shellhow would you use this string and both the lower and upper methods to create the string 'hello!hello!'hint answer many methods also take additional parameters between the parenthesesusing the more general syntaxobject method(parametersthe first of many such methods we will introduce is countsyntax for counts count(subcount and return the number of repetitions of string sub that appear as substrings inside the string read and make sure you see the answers are correcttale 'this is the best of times tale count(' ' tale count('is' tale count('that' tale count(' there is blank between the quotes in the line above blanks are characters like any other (except you can' see them)just as the parameter can be replaced by literal or any expressionthe object to which method is bound with the dot may also be given by literalor variable nameor any expression that evaluates to the right kind of object in its place this is true for any method call technically the dot between the object and the method name is an operatorand operators have different levels of precedence it is important to realize that this dot operator has the highest possible precedence read and see the difference parentheses make in the expressions'hello 'thereupper('hello there('hello 'there'upper('hello thereto see if you understand this precedencepredict the results of each line and then test in the shell 'xcount('xxx'( ' 'count('xxx'there are 'xxx' in ' 'but 'xxxin 'xxxpython lets you see all the methods that are bound to an object (and any object of its typewith the built-in function dir to see all string methodssupply the dir function with any string for exampletry in the shelldir(''many of the names in the list start and end with two underscoreslike __add__ these are all associated with methods and pieces of data used internally by the python interpreter you can ignore them for now the remaining entries in the list are all user-level methods for strings you should see lower and upper among them some of the methods are much more commonly used than others object notation use plus sign to concatenate the pieces lower( upper( objects and methods |
10,388 | object method(parametershas been illustrated so far with just the object type strbut it applies to all types later in the tutorial methods such as the following will be discussedif seq is listseq append(elementappends element to the end of the list if mydata is filemydata read(will read and return the entire contents of the file string indices string is sequence of smaller components (individual characters)and it is often useful to deal with parts of strings python indexes the characters in stringstarting from so for instancethe characters in the string 'computerhave indicescharacter index each index is associated with characterand you reference the individual characters much like in dictionary try the following (you can skip the comments that make the indices explicit enter in the shell 'computers[ [ [ you cannot refer directly to character that is not there indices only go to in the example above recall the len functionwhich gives the length of sequence it works on strings guess the following valueand test in the shelllen(sa common error is to think the last index will be the same as the length of the stringbut as you saw abovethat leads to an execution error if the length of some string is what is the index of its last characterwhat if the length is hopefully you did not count by ones all the way from the indices for string of length are the elements of the sequence range( )which goes from through - or the length of the string minus onewhich is - = or - in these examples sometimes you are interested in the last few elements of string and do not want to do calculations like this python makes it easy you can index from the right end of the string since positive integers are used to index from the frontnegative integers are used to index from the right endso the more complete table of indices for 'computergives two alternatives for each charactercharacter index index from the right end - - - - - - - - predict and test each individual linecontinuing in the shells[- [- [- it 'horselen(itit[- it[ stringspart iii |
10,389 | be careful remember what the initial index isstring slices it is also useful to extract larger pieces of string than single character that brings us to slices try this expression using slice notationcontinuing in the shells[ : note that [ is the first character past the slice the simplest syntax for slice of string issstartindex pastindex this refers to the substring of starting at index startindex and stopping just before index pastindex warningit confuses many people that the index after the colon is not the index of the final character in the slice the second index is past the end of the slice predict and try each line individually in the shells[ : [ : if you omit the first indexthe slice starts from the beginning if you omit the second indexthe slice goes all the way to the end predict and try each line individually in the shells[: [ : [:predict and try each line individually in the shellword 'programword[ : word[ :- word[ :word[ : word[: word[ :python evaluates slices in more forgiving manner than when indexing single characters in sliceif you give an index past limit of where it could bepython assumes you mean the actual end predict and try each line individually in the shellword[: word[ : enter slice expression using the variable word from above that produces 'graa useful string method that uses the ideas of indices and slices is find syntax options for find method with string ss find(subs find(substarts find(substartendreturn the integer index in the string of the beginning of the first complete occurrence of the substring sub if sub does not appear inside sreturn - the value - would be an impossible result if sub were foundso if - is returnedsub must not have been found if parameters start and end are not included in the parameter listthe search is objects and methods |
10,390 | through the whole string if an integer value is given for startthe search starts at index start if an integer value is given for endthe search ends before index end in other words if start and end appearthen the search is through the slice [start end]but the index returned is still counted from the beginning of for examplecheck that the following make sense the comment line is just there to help you count 'mississippis find(' ' find('si' find('sa'- find('si' predict and try each line in the shell line 'hellothere!line find(' 'line find('he'line find(' ' line find('he' we will consider more string methods laterbut we can already do useful things with the ones introduced inside the shellyou can look up documentation on any of the methods listed with the dir function here is place that you want to refer to the method itselfnot invoke the methodso note that you get help for find not for find(assuming you defined the string in the shell earliertry in the shell help( findthe python documentation uses square brackets to indicate optional elements which get default value if you leave them out this shortens the syntax descriptions if you want method documentation when you do not have variable of the type createdyou can also use the type name try in the shelldir(strhelp(str capitalizein the help documentation for function with one or more parametersyou may see what looks like final parameter ignore it it documents technical restriction on parameters it is not actually parameter indexing and slicing works on any kind of python sequenceso you can index or slice lists also readthis shell sessionvals [ vals[ vals[- vals[ : [ unlike stringslists are mutableas you will see in appending to list (page indices and slices can also be used in assignment statements to change listsbut in this tutorial we not need list indexingand we will not discuss this subject further stringspart iii |
10,391 | index variables all the concrete examples in the last two sections used literal numbers for the indices that is fine for learning the ideabut in practicevariables or expressions are almost always used for indices as usual the variable or expression is evaluated before being used try in idle and see that the example program index py makes senses 'wordprint('the full string is'sn len(sfor in range( )print(print(' ='iprint('the letter at index :' [ ]print('the part before index (if any):' [: ]print('the part before index + :' [: + ]we will use index variables in more practical situations as we explain more operations with strings split syntax options for the split method with string ss split( split(septhe 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 for exampleread and followtale 'this is the best of times tale split(['this''is''the''best''of''times ' 'mississippis split(' '[' ''ss''ss''pp''' split(no white space ['mississippi'predict and test each line in the shellline 'gotear some strings apart!seq line split(seq line split(':'line split('ar'lines 'this includes\\nsome new\\nlines lines split(join join is roughly the reverse of split it joins together sequence of strings the syntax is rather different the separator sep comes firstsince it has the right type ( stringsyntax for the join methodsep join(sequence objects and methods |
10,392 | return new string obtained by joining together the sequence of strings into one stringinterleaving the string sep between sequence elements for example (continuing in the shell from the previous sectionusing seq)followjoin(seq'gotear some strings apart!'join(seq'go:tearsomestringsapart!'//join(seq'go://tear//some//strings//apart!predict and try each linecontinuing in the shell'##join(seq':join(['one''two''three']the methods split and join are often used in sequenceunderscore exercise write program underscores py that would input phrase from the user and print out the phrase with the white space between words replaced by an underscore for instance if the input is the best onethen it would print the_best_one the conversion can be done in one or two statements using the recent string methods acronym exercise an acronym is string of capital letters formed by taking the first letters from phrase for examplesadd is an acronym for 'students against drunk drivingnote that the acronym should be composed of all capital letters even if the original words are not write program acronym py that has the user input phrase and then prints the corresponding acronym to get you startedhere are some things you will need to do first check that you understand the basic syntax to accomplish the different individual tasksindicate the proper syntax using python function or operation will allow you to accomplish each task invent appropriate variable names for the different parts these are not complete instructionsthe idea is to make sure you know the basic syntax to use in all these situations see the questions after the list to help you put together the final program what type of data will the input bewhat type of data will the output be get the phrase from the user convert to upper case divide the phrase into words initialize new empty listletters get the first letter of each word append the first letter to the list letters join the letters togetherwith no space between them print the acronym which of these steps is in loopwhat for statement controls this loopput these ideas together and write and test your program acronym py make sure you use names for the objects that are consistent from one line to the next(you might not have done that when you first considered the syntax and ideas needed for - above individually stringspart iii |
10,393 | further exploration as the dir(''list showedthere are many more operations on strings than we have discussedand there are further variations of the ones above with more parameters methods startswithendswithand replace are discussed later in more string methods (page if you want to reach systematic reference from inside idlego to help python docs library referenceand find the section built-in typesand then the subsection for type str many methods use features we have not discussed yetbut currently accessible methods are capitalizetitlestriprfind more classes and methods the classes and methods introduced here are all used in the revised mad lib program developed in the next section appending to list before making version of the madlib program that is much easier to use with new storieswe need couple of facts about other types of objects that are built into python so far we have used listsbut we have not changed the contents of lists the most obvious way to change list is to add new element onto the end lists have the method append it modifies the original list another word for modifiable is mutable lists are mutable most of the types of object considered so far (intstrfloatare immutable or not mutable read and see how the list named words changeswords list(words [words append('animal'words ['animal'words append('food'words ['animal''food'words append('city'words ['animal''food''city'this is particularly useful in loopwhere we can accumulate new list read the start of this simple exampledef multiplyall(numlistmultiplier)'''return new list containing all of the elements of numlisteach multiplied by multiplier for exampleprint(multiplyall([ ] )[ ''more to come clearly this will be repetitious we will process each element of the list numlist for-each loop with numlist is appropriate also we need to create more and more elements of the new list the accumulation pattern will work herewith couple of wrinkles test yourself if we are going to accumulate list how do we initialize the list objects and methods |
10,394 | in earlier versions of the accumulation loopwe needed an assignment statement to change the object doing the accumulatingbut now the method append modifies its list automaticallyso we do not need an assignment statement read and try the example program multiply pydef multiplyall(numlistmultiplier)# '''return new list containing all of the elements of numlisteach multiplied by multiplier for exampleprint(multiplyall([ ] )[ ''newlist list(for num in numlistnewlist append(num*multiplierreturn newlist print(multiplyall([ ] )# # # # # make sure the result makes sense to you or follow the details of playing computer below line - numlist [ [ [ [ [ [ [ [ [ [ multiplier newlist [[[ [ [ [ [ [ [ num comment definition call function set formal parameters first in list append * next in list append * last in list append * done with list and loop return [ print [ using for-loop and append is powerful and flexible way to derive new listbut not the only way sets list may contain duplicatesas in [ this is sometimes usefuland sometimes not you may have learned in math class that set is collection that does not allow repetitions ( set automatically removes repetitions suggestedpython has type set like many type namesit can be used to convert other types in this case it makes sense to convert any collectionand the process removes duplicates read and see what happensstrlist [' ''zz'' '' ''bb'' '' '' 'aset set(strlistaset {'bb''zz'' '' '' '(technicallya set is unorderedso your version of idle may list the set in different order set literals are enclosed in braces like other collectionsa set can be used as sequence in for loop readand check it makes sensefor in asetprint( more classes and methods |
10,395 | bb zz predict the result of the followingand then paste it into the shell and test (you may not guess python' orderbut see if you can get the right length and the right elements in some order set(['animal''food''animal''food''food''city']constructors we have now seen several examples of the name of type being used as function read these earlier examplesx int(' ' str( nums list(aset set(numberlistin all such cases new object of the specified type is constructed and returned such functions are called constructors mad libs revisited function to ease the creation of mad libs the versions so far of the mad lib program have been fairly easy to edit to contain different mad lib come up with new mad lib story as format string produce the list of cues to prompt the user with the first is creative process the second is pretty mechanical process of looking at the story string and copying out the embedded cues the first is best left to humans the second can be turned over to python function to do automaticallyas many times as we likewith any story if we write the code once writing the python code also takes different sort of creativitywe shall illustrate creative process this is bigger problem than any we have taken on so far it is hard to illustrate creative process if the overall problem is too simple try and follow along read the sample code and pseudo-code there is nothing to try in the shell or editor until further notice if we follow the last version of the mad lib programwe had loop iterating through the keys in the storyand making dictionary entry for each key the main idea we follow here is to use the format string to automatically generate the sequence of keys let us plan this unified task as new functiondef getkeys(formatstring)'''formatstring is format string with embedded dictionary keys return list containing all the keys from the format string ''more to come the keys we want are embedded like {animalthere may be any number of them in the format string this indeterminacy suggests loop to extract them at this point we have only considered for loops there is no obvious useful sequence to iterate through in the loop (we are trying to create such sequence!the only pattern we have discussed that does not actively process each element of significant list is repeat-loopwhere we just use the loop to objects and methods |
10,396 | repeat the correct number of times this will work in this case (there is more efficient approach after we introduce while statements (page )suggested in mad lib while exercise (page firsthow many times do we want to pull out key once for each embedded format so how do we count thosethe count method is obviously way to count however we must count fixed stringand the whole embedded formats varywith different keys in the middle common part is '{'and this should not appear in the regular text of the storyso it will serve our purposerepetitions formatstring count('{'for in range(repetitions)this is certainly the most challenging code to date before jumping into writing it all preciselywe can give an overall plan in pseudo-code for plan we need an idea of what quantities we are keeping track ofand name themand outline the sequence of operations with them think about data to namein this case we are trying to find list we will need to extract one element at time and add it to the listso we need listsay keylist the central task is to identifying the individual keys when we find key we can call it key think about identifying the text of individual keys this may be too hard to think of in the abstractso let us use as concrete exampleand let us keep it simple for the moment suppose the data in formatstring starts off as follows the lines with numbers are added to help us refer to the indices display of possible data 'blah {animalblah blah {foodstart of formatstring the first key is 'animalat formatstring[ : the next key is 'foodat formatstring[ : to identify each key as part of formatstring we need not only the variable formatstringbut also index variables to locate the start and end of the slices obvious names for the indices are start and end we want to keep them current so the next key slice will always be key formatstring[start endlet us now put this all in an overall plan we will have to continuously modify the start and end indicesthe keyand the list we have basic pattern for accumulating listinvolving initializing it and appending to it we can organize planpartly fleshed outwith couple of approximations still to be worked out the parts that are not yet in python are emphasizeddef getkeys(formatstring)keylist list(?other initializations ?repetitions formatstring count('{'for in range(repetitions)find the start and end of the next key key formatstring[start endkeylist append(keyreturn keylist we can see that the main piece left is to find the start and end indices for each key the important word is findthe method we consider is find as with the plan for using count abovethe beginnings of keys are identified by the specific string '{we can look first at mad libs revisited |
10,397 | formatstring find('{'but that is not the full solution if we look at our concrete examplethe value returned is not how in general would we locate the beginning of the slice we wantwe do not want the position of the '{'but the position just after the '{since the length of '{is the correct position is + we can generalize this to start formatstring find('{' okwhat about endclearly it is at the '}in this exampleformatstring find('}'gives us exactly the right place for the end of the slice (one place past the actual endthere is subtle issue here that will be even more important laterwe will keep wanting to find the next braceand not keep finding the first brace how do we fix thatrecall there was an alternate syntax for findspecifying the first place to searchthat is what we need where should we startwellthe end must come after the start of the keyour variable startstart formatstring find('{' end formatstring find('}'startfiguring out how to find the first key is importantbut we are not home free yet we need to come up with code that works in loop for the later keys this code will not work for the next one whyas writtenthe search for '{will again start from the beginning of the format stringand will find the first key again so what code will work for the second searchwe search for the start of the next key going from the end of the last onestart formatstring find('{'end end formatstring find('}'startthis code will also work for later times through the loopeach time uses the end from the previous time through the loop so now what do we do for finding the first keywe could separate the treatment of the first key from all the othersbut an easier approach would be to see if we can use the same code that already works for the later repetitionsand initialize variables right to make it work if we are to find the first key with start formatstring find('{'end then what do we needclearly end needs to have value (there will not be previous loop to give it value what value should we initialize it tothe first search starts from the beginning of the string at index the initialization goes before the loopso the full code for this function is def getkeys(formatstring)'''formatstring is format string with embedded dictionary keys return list containing all the keys from the format string ''keylist list(end repetitions formatstring count('{'for in range(repetitions)start formatstring find('{'end end formatstring find('}'startkey formatstring[start endkeylist append(key objects and methods |
10,398 | return keylist look the code over and see that it makes sense see how we continuously modify startendkeyand keylist since we have coded this new part as functionit is easy to test without running whole revised mad lib program we can just run this function on some test datalike the original storyand see what it does run the example program testgetkeys py'''test the function to extract keys from format string for dictionary ''def getkeys(formatstring)'''formatstring is format string with embedded dictionary keys return list containing all the keys from the format string ''keylist list(end repetitions formatstring count('{'for in range(repetitions)start formatstring find('{'end end formatstring find('}'startkey formatstring[start endkeylist append(keyreturn keylist originalstory ""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 ""print(getkeys(originalstory)the functions should behave as advertised look back on the process described to come up with the getkeys function one way of approaching the creative process of coding this function was provided there are many other results and approaches possiblebut the discussion did illustrate number of useful ideas which you might adapt to other problemsin different orders and proportionsthat are summarized in the next section creative problem solving steps clearly define the problem encapsulating the problem in function is usefulwith inputs as parameters and results returned include complete documentation stringand clear example (or examplesof what it is to do if the problem is too complicated to just solve easilystraight awayit is often useful to construct representative concrete case and write down concrete steps appropriate to this problem think of the data in the problemand give names to the pieces you will need to refer to clearly identify the mad libs revisited |
10,399 | ideas that the names correspond to when using sequences like lists or stringsyou generally need names not only for the whole collectionbut also parts like items and characters or substringsand often indices that locate parts of the collection plan the overall approach to the problem using mixture of python and suggestive phrases (called pseudo-codethe idea is to refine it to place where you can fairly easily figure how to replace the phrases with python replace your pseudo-code parts with python if you had concrete example to guide youyou may want to test with one of more further concrete examples with different specific datato make sure you come up with code for generalization that works in all cases this is the process of abstraction recognize where something is being repeated over and overand think how to structure appropriate loops can you incorporate any patterns you have seen beforeif you need to create successive modification loopthink of how to approach the first repetition and then how to modify the data for the later times through the loop usually you can make the first time through the loop fit the more general pattern needed for the repetitions by making appropriate initializations before the loop check and test your codeand correct as necessary the revised mad lib program there is still an issue for use of getkeys in the mad lib programthe returned list has unwanted repetitions in it we can easily create collection without repetitionshowone approach is to make set from the list returned neater approach would be to just have the getkeys function return set in the first place we need to slightly change to getkeysdocumentation string and the final return line this will be included in new version of the mad lib programwhich makes it easy to substitute new story we will make the story' format string be parameter to the central methodtellstory we will also put the clearly identified step of filling the dictionary with the user' picks in separate function we will test tellstory with the original story note the changes included in madlib py and run""madlib py interactive display of mad libwhich is provided as python format stringwith all the cues being dictionary formatsin the form {cuein this versionthe cues are extracted from the story automaticallyand the user is prompted for the replacements original verison adapted from code of kirby urner ""def getkeys(formatstring)'''formatstring is format string with embedded dictionary keys return set containing all the keys from the format string ''keylist list(end repetitions formatstring count('{'for in range(repetitions)start formatstring find('{'end pass the '{end formatstring find('}'startkey formatstring[start endkeylist append(keymay add duplicates return set(keylistremoves duplicatesno duplicates in set objects and methods |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.