id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
19,600 | sequencesstringslistsand files objectives to understand the string data type and how strings are represented in the computer to be familiar with various operations that can be performed on strings through built-in functions and string methods to understand the basic idea of sequences and indexing as they apply to python strings and lists to be able to apply string formatting to produce attractiveinformative program output to understand basic file processing concepts and techniques for reading and writing text files in python to understand basic concepts of cryptography to be able to understand and write programs that process textual information the string data type so farwe have been discussing programs designed to manipulate numbers and graphics but you know that computers are also important for storing and operating on textual information in factone of the most common uses for personal computers is word processing this focuses on textual applications to introduce some important ideas about how text is stored on the computer you may not think that word-based applications are all that excitingbut as you'll soon seethe basic ideas presented here are at work in virtually all areas of computingincluding powering the the world-wide web text is represented in programs by the string data type you can think of string as sequence of characters in you learned that string literal is formed by enclosing some characters in quotation marks python also allows strings to be delimited by single quotes (apostrophes |
19,601 | there is no differencejust be sure to use matching set strings can also be saved in variablesjust like any other data here are some examples illustrating the two forms of string literalsstr "hellostr 'spamprint(str str hello spam type(str type(str you already know how to print strings you have also seen how to get string input from users recall that the input function returns whatever the user types as string object that means when you want to get stringyou can use the input in its "raw(non evaledform here' simple interaction to illustrate the pointfirstname input("please enter your name"please enter your namejohn print("hello"firstnamehello john notice how we saved the user' name with variable and then used that variable to print the name back out again so farwe have seen how to get strings as inputassign them to variablesand how to print them out that' enough to write parrot programbut not to do any serious text-based computing for thatwe need some string operations the rest of this section takes you on tour of the more important python string operations in the following sectionwe'll put these ideas to work in some example programs what kinds of things can we do with stringsfor startersremember what string isa sequence of characters one thing we might want to do is access the individual characters that make up the string in pythonthis can be done through the operation of indexing we can think of the positions in string as being numberedstarting from the left with figure illustrates with figure indexing of the string "hello bobthe string "hello bob indexing is used in string expressions to access specific character position in the string the general form for indexing is [the value of the expression determines which character is selected from the string here are some interactive indexing examples |
19,602 | greet "hello bobgreet[ 'hprint(greet[ ]greet[ ]greet[ ] print(greet[ - ] notice thatin string of charactersthe last character is at position because the indexes start at this is probably also good time to remind you about the difference between string objects and the actual printed output in the interactions above the python shell shows us the value of strings by putting them in single quotesthat' python' way of communicating to us that we are looking at string object when we actually print the stringpython does not put any quotes around the sequence of characters we just get the text contained in the string by the waypython also allows indexing from the right end of string using negative indexes greet[- 'bgreet[- 'bthis is particularly handy for getting at the last character of string indexing returns string containing single character from larger string it is also possible to access contiguous sequence of characters or substring from string in pythonthis is accomplished through an operation called slicing you can think of slicing as way of indexing range of positions in the string slicing takes the form [:both start and end should be int-valued expressions slice produces the substring starting at the position given by start and running up tobut not includingposition end continuing with our interactive examplehere are some slicesgreet[ : 'helgreet[ : bobgreet[: 'hellogreet[ :bobgreet[:'hello bobthe last three examples show that if either expression is missingthe start and end of the string are the assumed defaults the final expression actually hands back the entire string |
19,603 | operator len(for in meaning concatenation repetition indexing slicing length iteration through characters table python string operations indexing and slicing are useful operations for chopping strings into smaller pieces the string data type also supports operations for putting strings together two handy operators are concatenation (+and repetition (*concatenation builds string by "gluingtwo strings together repetition builds string by multiple concatenations of string with itself another useful function is lenwhich tells how many characters are in string finallysince strings are sequences of charactersyou can iterate through the characters using python for loop here are some examples of various string operations"spam"eggs'spameggs"spam"and"eggs'spamandeggs "spam'spamspamspam"spam 'spamspamspamspamspam( "spam"("eggs 'spamspamspameggseggseggseggseggslen("spam" len("spamandeggs" for ch in "spam!"print(chend=" these basic string operations are summarized in table simple string processing now that you have an idea what various string operations can dowe're ready to write some programs our first example is program to compute the usernames for computer system |
19,604 | many computer systems use username and password combination to authenticate system users the system administrator must assign unique username to each user oftenusernames are derived from the user' actual name one scheme for generating usernames is to use the user' first initial followed by up to seven letters of the user' last name using this methodthe username for elmer thudpucker would be "ethudpuc,and john smith would just be "jsmith we want to write program that reads person' name and computes the corresponding username our program will follow the basic inputprocessoutput pattern for brevityi will skip discussion of the algorithm development and jump right to the code the outline of the algorithm is included as comments in the final program username py simple string processing program to generate usernames def main()print("this program generates computer usernames \ "get user' first and last names first input("please enter your first name (all lowercase)"last input("please enter your last name (all lowercase)"concatenate first initial with chars of the last name uname first[ last[: output the username print("your username is:"unamemain(this program first uses input to get strings from the user then indexingslicingand concatenation are combined to produce the username here' an example runthis program generates computer usernames please enter your first name (all lowercase)elmer please enter your last name (all lowercase)thudpucker your username isethudpuc do you see where the blank line between the introduction and the prompt for the first name comes fromputting the newline character (\nat the end of the string in the first print statement caused the output to skip down an extra line this is simple trick for putting some extra white space into the output to make it look little better here is another problem that we can solve with string operations suppose we want to print the abbreviation of the month that corresponds to given month number the input to the pro |
19,605 | gram is an int that represents month number ( - )and the output is the abbreviation for the corresponding month for exampleif the input is then the output should be marfor march at firstit might seem that this program is beyond your current ability experienced programmers recognize that this is decision problem that iswe have to decide which of different outputs is appropriatebased on the number given by the user we will not cover decision structures until laterhoweverwe can write the program now by some clever use of string slicing the basic idea is to store all the month names in big string months "janfebmaraprmayjunjulaugsepoctnovdecwe can lookup particular month by slicing out the appropriate substring the trick is computing where to slice since each month is represented by three lettersif we knew where given month started in the stringwe could easily extract the abbreviation monthabbrev months[pos:pos+ this would get us the substring of length three that starts in the position indicated by pos how do we compute this positionlet' try few examples and see what we find remember that string indexing starts at month jan feb mar apr number position of coursethe positions all turn out to be multiples of to get the correct multiplewe just subtract from the month number and then multiply by so for we get ( and for we have ( now we're ready to code the program againthe final result is short and sweetthe comments document the algorithm we've developed month py program to print the abbreviation of monthgiven its number def main()months is used as lookup table months "janfebmaraprmayjunjulaugsepoctnovdecn eval(input("enter month number ( - )")compute starting position of month in months pos ( - grab the appropriate slice from months |
19,606 | monthabbrev months[pos:pos+ print the result print("the month abbreviation is"monthabbrev "main(notice the last line of this program uses string concatenation to put period at the end of the month abbreviation here is sample of program outputenter month number ( - ) the month abbreviation is apr one weakness of the "string as lookup tableapproach used in this example is that it will only work when the substrings all have the same length (in this casethreesuppose we want to write program that outputs the complete month name for given number how could that be accomplished lists as sequences strictly speaking the operations in table are not really just string operations they are operations that apply to sequences as you know from the discussion in python lists are also kind of sequence that means we can also indexsliceand concatenate listsas the following session illustrates[ , [ , [ [ , ]* [ grades [' ',' ',' ',' ',' 'grades[ 'agrades[ : [' '' 'len(grades one of the nice things about lists is that they are more general than strings strings are always sequences of characterswhereas lists can be sequences of arbitrary objects you can create list of numbers or list of strings in factyou can even mix it up and create list that contains both numbers and stringsmylist [ "spam" " " |
19,607 | in later we'll put all sorts of things into lists like pointsrectanglesdicebuttonsand even studentsusing list of stringswe can rewrite our month abbreviation program from the previous section and make it even simpler month py program to print the month abbreviationgiven its number def main()months is list used as lookup table months ["jan""feb""mar""apr""may""jun""jul""aug""sep""oct""nov""dec" eval(input("enter month number ( - )")print("the month abbreviation is"months[ - "main(there are couple of things you should notice about this program have created list of strings called months to use as the lookup table the code that creates the list is split over two lines normally python statement is written on single linebut in this case python knows that the list isn' finished until the closing bracket "]is encountered breaking the statement across two lines like this makes the code more readable listsjust like stringsare indexed starting with so in this list the value months[ is the string "janin generalthe nth month is at position - since this computation is straightforwardi didn' even bother to put it in separate stepthe expression months[ - is used directly in the print statement not only is this solution to the abbreviation problem bit simplerit is also more flexible for exampleit would be trivial to change the program so that it prints out the entire name of the month all we need is new definition of the lookup list months ["january""february""march""april""may""june""july""august""september""october""november""december"while strings and lists are both sequencesthere is an important difference between the two lists are mutable that means that the value of an item in list can be modified with an assignment statement stringson the other handcannot be changed "in place here is an example interaction that illustrates the differencemylist [ |
19,608 | mylist[ mylist[ mylist [ mystring "hello worldmystring[ 'lmystring[ 'ztraceback (most recent call last)file ""line in typeerror'strobject does not support item assignment the first line creates list of four numbers indexing position returns the value (as usualindexes start at the next command assigns the value to the item in position after the assignmentevaluating the list shows that the new value has replaced the old attempting similar operation on string produces an error strings are not mutablelists are string representation and message encoding string representation hopefullyyou are starting to get the hang of computing with textual (stringdata howeverwe haven' yet discussed how computers actually manipulate strings in you saw that numbers are stored in binary notation (sequences of zeros and ones)the computer cpu contains circuitry to do arithmetic with these representations textual information is represented in exactly the same way underneathwhen the computer is manipulating textit is really no different from number crunching to understand thisyou might think in terms of messages and secret codes consider the age-old grade school dilemma you are sitting in class and want to pass note to friend across the room unfortunatelythe note must pass through the handsand in front of the curious eyesof many classmates before it reaches its final destination andof coursethere is always the risk that the note could fall into enemy hands (the teacher'sso you and your friend need to design scheme for encoding the contents of your message one approach is to simply turn the message into sequence of numbers you could choose number to correspond to each letter of the alphabet and use the numbers in place of letters without too much imaginationyou might use the numbers - to represent the letters - instead of the word "sourpuss,you would write " to those who don' know the codethis looks like meaningless string of numbers for you and your friendhoweverit represents word this is how computer represents strings each character is translated into numberand the entire string is stored as sequence of (binarynumbers in computer memory it doesn' really matter what number is used to represent any given character as long as the computer is consistent |
19,609 | sequencesstringslistsand files about the encoding/decoding process in the early days of computingdifferent designers and manufacturers used different encodings you can imagine what headache this was for people transferring data between different systems consider situation that would result ifsaypcs and macintosh computers each used their own encoding if you type term paper on pc and save it as text filethe characters in your paper are represented as certain sequence of numbers thenif the file was read into your instructor' macintosh computerthe numbers would be displayed on the screen as different characters from the ones you typed the result would be gibberishto avoid this sort of problemcomputer systems today use industry standard encodings one important standard is called ascii (american standard code for information interchangeascii uses the numbers through to represent the characters typically found on an (americancomputer keyboardas well as certain special values known as control codes that are used to coordinate the sending and receiving of information for examplethe capital letters - are represented by the values - and the lowercase versions have codes - one problem with the ascii encodingas its name impliesis that it is american-centric it does not have symbols that are needed in many other languages extended ascii encodings have been developed by the international standards organization to remedy this situation most modern systems are moving to the support of unicodea much larger standard that includes support for the characters of nearly all written languages python strings support the unicode standardso you can wrangle characters from just about any languageprovided your operating system has appropriate fonts for displaying the characters python provides couple of built-in functions that allow us to switch back and forth between characters and the numeric values used to represent them in strings the ord function returns the numeric ("ordinal"code of single-character stringwhile chr goes the other direction here are some interactive examplesord(" " ord(" " chr( 'achr( 'zif you're reading very carefullyyou might notice that these results are consistent with the ascii encoding of characters that mentioned above by designunicode uses the same codes as ascii for the characters originally defined there but unicode includes many more exotic characters as well for examplethe greek letter pi is character and the symbol for the euro is character there' one more piece in the puzzle of how to store characters in computer memory as you know from the underlying cpu deals with memory in fixed-sized pieces the smallest addressable piece is typically bitswhich is called byte of memory single byte can store |
19,610 | different values that' more than enough to represent every possible ascii character (in factascii is only bit codebut single byte is nowhere near sufficient for storing all the , possible unicode characters to get around this problemthe unicode standard defines various encoding schemes for packing unicode characters into sequences of bytes the most common encoding is called utf- utf- is variable-length encoding that uses single byte to store characters that are in the ascii subsetbut may need up to bytes in order to represent some of the more esoteric characters that means that string of length characters will end up getting stored in memory as sequence of between and bytesdepending on the actual characters used in the string as rule of thumb for latin alphabets (the usualwesterncharacters)howeverit' pretty safe to estimate that character requires about byte of storage on average programming an encoder let' return to the note-passing example using the python ord and chr functionswe can write some simple programs that automate the process of turning messages into sequences of numbers and back again the algorithm for encoding the message is simple get the message to encode for each character in the messageprint the letter number of the character getting the message from the user is easyan input will take care of that for us message input("please enter the message to encode"implementing the loop requires bit more effort we need to do something for each character of the message recall that for loop iterates over sequence of objects since string is kind of sequencewe can just use for loop to run through all the characters of the message for ch in messagefinallywe need to convert each character to number the simplest approach is to use the unicode number (provided by ordfor each character in the message here is the final program for encoding the messagetext numbers py program to convert textual message into sequence of numbersutilizing the underlying unicode encoding def main()print("this program converts textual message into sequence"print("of numbers representing the unicode encoding of the message \ "get the message to encode message input("please enter the message to encode" |
19,611 | print("\nhere are the unicode codes:"loop through the message and print out the unicode values for ch in messageprint(ord(ch)end="print(blank line before prompt main(we can use the program to encode important messages this program converts textual message into sequence of numbers representing the unicode encoding of the message please enter the message to encodewhat sourpusshere are the unicode codes one thing to notice about this result is that even the space character has corresponding unicode number it is represented by the value string methods programming decoder now that we have program to turn message into sequence of numbersit would be nice if our friend on the other end had similar program to turn the numbers back into readable message let' solve that problem next our decoder program will prompt the user for sequence of unicode numbers and then print out the text message with the corresponding characters this program presents us with couple of challengeswe'll address these as we go along the overall outline of the decoder program looks very similar to the encoder program one change in structure is that the decoding version will collect the characters of the message in string and print out the entire message at the end of the program to do thiswe need to use an accumulator variablea pattern we saw in the factorial program from here is the decoding algorithmget the sequence of numbers to decode message "for each number in the inputconvert the number to the corresponding unicode character add the character to the end of message print message |
19,612 | before the loopthe accumulator variable message is initialized to be an empty stringthat is string that contains no characters (""each time through the loop number from the input is converted into an appropriate character and appended to the end of the message constructed so far the algorithm seems simple enoughbut even the first step presents us with problem how exactly do we get the sequence of numbers to decodewe don' even know how many numbers there will be to solve this problemwe are going to rely on some more string manipulation operations firstwe will read the entire sequence of numbers as single string using input then we will split the big string into sequence of smaller stringseach of which represents one of the numbers finallywe can iterate through the list of smaller stringsconvert each into numberand use that number to produce the corresponding unicode character here is the complete algorithmget the sequence of numbers as stringinstring split instring into sequence of smaller strings message "for each of the smaller stringschange the string of digits into the number it represents append the unicode character for that number to message print message this looks complicatedbut python provides some functions that do just what we need you may have noticed all along that 've been talking about string objects remember from last objects have both data and operations (they "know stuff,and "do stuff "by virtue of being objectsstrings have some built-in methods in addition to the generic sequence operations that we have used so for we'll use some of those abilities here to solve our decoder problem for our decoderwe will make use of the split method this method splits string into list of substrings by defaultit will split the string wherever space occurs here' an examplemystring "hellostring methods!mystring split(['hello,''string''methods!'naturallythe split operation is called using the usual dot notation for invoking one of an object' methods in the resultyou can see how split has turned the original string "hellostring methods!into list of three substringsstrings"hello,""string"and "methods!by the waysplit can be used to split string at places other than spaces by supplying the character to split on as parameter for exampleif we have string of numbers separated by commaswe could split on the commas " , , , split(","[' '' '' '' 'since our decoder program should accept the same format that was produced by the encoder programnamely sequence of numbers with spaces betweenthe default version of split works nicely |
19,613 | " split([' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' 'notice that the resulting list is not list of numbersit is list of strings it just so happens these strings contain only digits and could be interpreted as numbers all that we need now is way of converting string containing digits into python number of coursewe already know one way of doing thatwe just need to evaluate the string with eval recalleval takes string and evaluates it as if it were python expression as refresherhere are some interactive examples of evalnumstr " eval(numstr eval(" " eval(" + " eval(" " eval(("enter number ")enter number print using split and eval we can write our decoder program numbers text py program to convert sequence of unicode numbers into string of text def main()print("this program converts sequence of unicode numbers into"print("the string of text that it represents \ "get the message to encode instring input("please enter the unicode-encoded message"loop through each substring and build unicode message message "for numstr in instring split()codenum eval(numstrconvert digits to number |
19,614 | message message chr(codenumconcatentate character to message print("\nthe decoded message is:"messagemain(study this program bitand you should be able to understand exactly how it accomplishes its task the heart of the program is the loop for numstr in instring split()codenum eval(numstrmessage message chr(codenumthe split function produces list of (sub)stringsand numstr takes on each successive string in the list called the loop variable numstr to emphasize that its value is string of digits that represents some number each time through the loopthe next substring is converted to number by evaling it this number is converted to the corresponding unicode character via chr and appended to the end of the accumulatormessage when the loop is finishedevery number in instring has been processed and message contains the decoded text here is an example of the program in actionimport numbers text this program converts sequence of unicode numbers into the string of text that it represents please enter the unicode-encoded message the decoded message isstrings are funmore string methods now we have couple of programs that can encode and decode messages as sequences of unicode values these programs turned out to be quite simple due to the power both of python' string data type and its built-in sequence operations and string methods python is very good language for writing programs that manipulate textual data table lists some other useful string methods good way to learn about these operations is to try them out interactively "helloi came here for an arguments capitalize('helloi came here for an arguments title('helloi came here for an argument |
19,615 | lower('helloi came here for an arguments upper('helloi came here for an arguments replace(" ""you"'helloyou came here for an arguments center( 'helloi came here for an arguments center( helloi came here for an argument count(' ' find(',' join(["number""one,""the""larch"]'number onethe larch"spamjoin(["number""one,""the""larch"]'numberspamone,spamthespamlarchi should mention that many of these functionslike splitaccept additional parameters to customize their operation python also has number of other standard libraries for text-processing that are not covered here you can consult the online documentation or python reference to find out more function capitalize( center(widths count(subs find(subs join(lists ljust(widths lower( lstrip( replace(oldsub,newsubs rfind(subs rjust(widths rstrip( split( title( upper(meaning copy of with only the first character capitalized copy of centered in field of given width count the number of occurrences of sub in find the first position where sub occurs in concatenate list into stringusing as separator like centerbut is left-justified copy of in all lowercase characters copy of with leading white space removed replace all occurrences of oldsub in with newsub like findbut returns the rightmost position like centerbut is right-justified copy of with trailing white space removed split into list of substrings (see textcopy of with first character of each word capitalized copy of with all characters converted to upper case table some string methods |
19,616 | lists have methods too in the last section we took look at some of the methods for manipulating string objects like stringslists are also objects and come with their own set of "extraoperations since this is primarily concerned with text-processingwe'll save the detailed discussion of various list methods for for later howeveri do want to introduce one important list method herejust to whet your appetite the append method can be used to add an item at the end of list this is often used to build list one item at time here' fragment of code that creates list of the squares of the first natural numberssquares [for in range( , )squares append( *xin this example we start with an empty list ([]and each number from to is squared and appended to the list when the loop is donesquares will be the list[ this is really just the accumulator pattern at work againthis time with our accumulated value being list with the append method in handwe can go back and address weakness in our little decoder program as we left itour program used string variable as an accumulator for the decoded output message because strings are immutablethis is somewhat inefficient the statement message message chr(codenumessentially creates complete copy of the message so far and tacks one more character on the end as the we build up the messagewe keep recopying longer and longer stringjust to add single new character at the end one way to avoid recopying the message over and over again is to use list the message can be accumulated as list of characters where each new character is appended to the end of the existing list rememberlists are mutableadding at the end of the list changes the list "in place,without having to copy the existing contents over to new object once we have accumulated all the characters in listwe can use the join operation to concatenate the characters into string in one fell swoop here' version of the decoder that uses this more efficient approach numbers text py program to convert sequence of unicode numbers into string of text efficient version using list accumulator def main()print("this program converts sequence of unicode numbers into"print("the string of text that it represents \ " |
19,617 | get the message to encode instring input("please enter the unicode-encoded message"loop through each substring and build unicode message chars [for numstr in instring split()codenum eval(numstrconvert digits to number chars append(chr(codenum)accumulate new character message "join(charsprint("\nthe decoded message is:"messagemain(in this codewe collect the characters be appending them to list called chars the final message is obtained by joining these characters together using and empty string as the separator so the original characters are concatenated together without any extra spaces between this is the standard way of accumulating string in python from encoding to encryption we have looked at how computers represent strings as sort of encoding problem each character in string is represented by number that is stored in the computer as binary representation you should realize that there is nothing really secret about this code at all in factwe are simply using an industry-standard mapping of characters into numbers anyone with little knowledge of computer science would be able to crack our code with very little effort the process of encoding information for the purpose of keeping it secret or transmitting it privately is called encryption the study of encryption methods is an increasingly important sub-field of mathematics and computer science known as cryptography for exampleif you shop over the internetit is important that your personal information such as your name and credit card number be transmitted using encodings that keep it safe from potential eavesdroppers on the network our simple encoding/decoding programs use very weak form of encryption known as substitution cipher each character of the original messagecalled the plaintextis replaced by corresponding symbol (in our case numberfrom cipher alphabet the resulting code is called the ciphertext even if our cipher were not based on the well-known unicode encodingit would still be easy to discover the original message since each letter is always encoded by the same symbola codebreaker could use statistical information about the frequency of various letters and some simple trial and error testing to discover the original message such simple encryption methods may be sufficient for grade-school note passingbut they are certainly not up to the task of securing communication over global networks modern approaches to encryption start by translating message into numbersmuch like our |
19,618 | encoding program then sophisticated mathematical algorithms are employed to transform these numbers into other numbers usuallythe transformation is based on combining the message with some other special value called the key in order to decrypt the messagethe party on the receiving end needs to have an appropriate key so that the encoding can be reversed to recover the original message encryption approaches come in two flavorsprivate key and public key in private key (also called shared keysystem the same key is used for encrypting and decrypting messages all parties that wish to communicate need to know the keybut it must be kept secret from the outside world this is the usual system that people think of when considering secret codes in public key systemsthere are separate but related keys for encrypting and decrypting knowing the encryption key does not allow you to decrypt messages or discover the decryption key in public key systemthe encryption key can be made publicly availablewhile the decryption key is kept private anyone can safely send message using the public key for encryption only the party holding the decryption key will be able to decipher it for examplea secure web site can send your web browser its public keyand the browser can use it to encode your credit card information before sending it on the internet then only the company that is requesting the information will be able to decrypt and read it using the proper private key input/output as string manipulation even programs that we may not view as primarily doing text manipulation often need to make use of string operations for exampleconsider program that does financial analysis some of the information ( datesmust be entered as strings after doing some number crunchingthe results of the analysis will typically be nicely formatted report including textual information that is used to label and explain numberschartstablesand figures string operations are needed to handle these basic input and output tasks example applicationdate conversion as concrete examplelet' extend our month abbreviation program to do date conversions the user will input date such as ",and the program will display the date as "may here is the algorithm for our programinput the date in mm/dd/yyyy format (datestrsplit datestr into monthday and year strings convert the month string into month number use the month number to lookup the month name create new date string in form month dayyear output the new date string we can implement the first two lines of our algorithm directly in code using string operations we have already discussed |
19,619 | sequencesstringslistsand files datestr input("enter date (mm/dd/yyyy)"monthstrdaystryearstr datestr split("/"here have gotten the date as string and split it at the slashes then "unpackedthe list of three strings into the variables monthstrdaystrand yearstr using simultaneous assignment the next step is to convert monthstr into an appropriate number in the unicode decoding programwe used the eval function to convert from string data type into numeric data type recall that eval evaluates string as python expression it is very general and can be used to turn strings into nearly any other python data type it' the swiss army knife of string conversion you can also convert strings into numbers using the python numeric type conversion functions (int()float())that were covered in here are some quick examples int(" " float(" " float(" " int(" "traceback (most recent call last)file ""line in valueerrorinvalid literal for int(with base ' as the last example showsthe string passed to these conversion functions must be numeric literal of the appropriate formotherwise you will get an error there is one subtle "gotchato consider when choosing between eval(and int(to convert strings into numbers python does not allow an int literal to have any leading zeroes as resultattempting to eval string that contains leading will produce an error on the other handthe int function handles this case without problem int(" " int(" " int(" " eval(" "traceback (most recent call last)file ""line in file ""line syntaxerrorinvalid token in older versions of pythonliterals with leading were taken to be octal (base values |
19,620 | in general thenif you're converting something that supposed to be an intit' safest to use int rather than eval returning to the date conversion algorithmwe can turn monthstr into number using int and then use this value to look up the correct month name here is the codemonths ["january""february""march""april""may""june""july""august""september""october""november""december"monthstr months[int(monthstr)- remember the indexing expression int(monthstr)- is used because list indexes start at the last step in our program is to piece together the date in the new format print("the converted date is:"monthstrdaystr+","yearstrnotice how have used concatenation for the comma immediately after the day here' the complete programdateconvert py converts date in form "mm/dd/yyyyto "month dayyeardef main()get the date datestr input("enter date (mm/dd/yyyy)"split into components monthstrdaystryearstr datestr split("/"convert monthstr to the month name months ["january""february""march""april""may""june""july""august""september""october""november""december"monthstr months[int(monthstr)- output result in month dayyear format print("the converted date is:"monthstrdaystr+","yearstrmain(when runthe output looks like thisenter date (mm/dd/yyyy)the converted date ismay this simple example didn' show itbut often it is also necessary to turn number into string in pythonmost data types can be converted into strings using the str function here are couple of simple examples |
19,621 | str( ' value str(value' print("the value is"str(value"the value is notice particularly the last example by turning value into stringwe can use string concatenation to put period at the end of sentence if we didn' first turn value into stringpython would interpret the as numerical operation and produce an errorbecause is not number we now have complete set of operations for converting values among various python data types table summarizes these four python type conversion functionsfunction float(int(str(eval(meaning convert expr to floating point value convert expr to an integer value return string representation of expr evaluate string as an expression table type conversion functions one common reason for converting number into string is so that string operations can be used to control the way the value is printed for examplea program performing date calculations would have to manipulate the monthdayand year as numbers for nicely formatted outputthese numbers would be converted back to strings just for funhere is program that inputs the daymonthand year as numbers and then prints out the date in two different formatsdateconvert py converts day month and year numbers into two date formats def main()get the day month and year daymonthyear eval(input("please enter daymonthand year numbers")date str(month)+"/"+str(day)+"/"+str(yearmonths ["january""february""march""april""may""june""july""august""september""october""november""december"monthstr months[month- date monthstr+str(day"str(year |
19,622 | print("the date is"date "or"date +"main(notice how string concatenation is used to produce the required output here is how the result looksplease enter daymonthand year numbers the date is or may string formatting as you have seenbasic string operations can be used to build nicely formatted output this technique is useful for simple formattingbut building up complex output through slicing and concatenation of smaller strings can be tedious python provides powerful string formatting operation that makes the job much easier let' start with simple example here is run of the change counting program from last change counter please enter the count of each coin type how many quarters do you have how many dimes do you have how many nickels do you have how many pennies do you have the total value of your change is notice that the final value is given as fraction with only one decimal place this looks funnysince we expect the output to be something like $ we can fix this problem by changing the very last line of the program as followsprint("the total value of your change is ${ : }format(total)now the program prints this messagethe total value of your change is $ let' try to make some sense of this the format method is built-in for python strings the idea is that the string serves as sort of template and values supplied as parameters are plugged into this template to form new string so string formatting takes the formformat( |
19,623 | sequencesstringslistsand files curly braces ({}inside the template-string mark "slotsinto which the provided values are inserted the information inside the curly braces tells which value goes in the slot and how the value should be formatted the python formatting operator is very flexiblewe'll cover just some basics hereyou can consult python reference if you' like all of the details in this bookthe slot descriptions will always have the form{:the index tells which of the parameters is inserted into the slot as usual in pythonindexing starts with in the example abovethere is single slot and the index is used to say that the first (and onlyparameter is inserted into that slot the part of the description after the colon specifies how the value should look when it is inserted into the slot again returning to the examplethe format specifier is the format of this specifier is the width specifies how many "spacesthe value should take up if the value takes up less than the specified widthit is space is padded (by default with the space characterif the value requires more space than allottedit will take as much space as is required to show the value so putting here essentially says "use as much space as you need the precision is which tells python to round the value to two decimal places finallythe type character says the value should be displayed as fixed point number that means that the specified number decimal places will always be showneven if they are zero complete description of format specifiers is pretty hairybut you can get good handle on what' possible just by looking at few examples the simplest template strings just specify where to plug in the parameters "hello { { }you may have already won ${ }format("mr ""smith" 'hello mr smithyou may have already won $ oftenyou'll want to control the width and/or precision of numeric value "this int{ : }was placed in field of width format( 'this int was placed in field of width "this int{ : }was placed in field of width format( 'this int was placed in field of width "this float{ : }has width and precision format( 'this float has width and precision "this float{ : }is fixed at decimal placesformat( 'this float is fixed at decimal places"this float{ : }has width and precision format( as of python the index portion of the slot description is optional when the indexes are omittedthe parameters are just filled into the slots in left-to-right fashion |
19,624 | 'this float has width and precision "compare { and { : }format( 'compare and notice that for normal (not fixed-pointfloating point numbersthe precision specifies the number of significant digits to print for fixed-point (indicated by the at the end of the specifierthe precision gives the number of decimal places in the last examplethe same number is printed out in two different formats it illustrates that if you print enough digits of floating-point numberyou will almost always find "surprise the computer can' represent exactly as floatingpoint number the closest value it can represent is ever so slightly larger than if not given an explicit precisionpython will print the number out to few decimal places the slight extra amount shows up if you print lots of digits generallypython only displays closely rounded version of float using explicit formatting allows you to see the full result down to the last bit you may notice thatby defaultnumeric values are right-justified this is helpful for lining up numbers in columns stringson the other handare left-justified in their fields you can change the default behaviors by including an explicit justification character at the beginning of the format specifier the necessary characters are and for leftrightand center justificationrespectively "left justification{ :< }format("hi!"'left justificationhi"right justification{ :> }format("hi!"'right justificationhi!"centered{ :^ }format("hi!"'centeredhibetter change counter let' close our formatting discussion with one more example program given what you have learned about floating point numbersyou might be little uneasy about using them to represent money suppose you are writing computer system for bank your customers would not be too happy to learn that check went through for an amount "very close to $ they want to know that the bank is keeping precise track of their money even though the amount of error in given value is very smallthe small errors can be compounded when doing lots of calculationsand the resulting error could add up to some real cash that' not satisfactory way of doing business better approach would be to make sure that our program used exact values to represent money we can do that by keeping track of the money in cents and using an int to store it we can then convert this into dollars and cents in the output step assuming we are dealing with positive amountsif total represents the value in centsthen we can get the number of dollars by integer division total / and the cents from total both of these are integer calculations andhencewill give us exact results here is the updated program |
19,625 | change py program to calculate the value of some change in dollars this version represents the total cash in cents def main()print("change counter\ "print("please enter the count of each coin type "quarters eval(input("quarters")dimes eval(input("dimes")nickels eval(input("nickels")pennies eval(input("pennies")total quarters dimes nickels pennies print("the total value of your change is ${ { : > }format(total// total% )main( have split the final print statement across two lines normally statement ends at the end of the line sometimes it is nicer to break long statement into smaller pieces because this line is broken in the middle of the print functionpython knows that the statement is not finished until the final closing parenthesis is reached in this caseit is okand preferableto break the statement across two lines rather than having one really long line the string formatting in the print statement contains two slotsone for dollars as an int and one for cents the cents slot illustrates one additional twist on format specifiers the value of cents is printed with the specifier > the zero in front of the justification character tells python to pad the field (if necessarywith zeroes instead of spaces this ensures that value like dollars and cents prints as $ rather than $ by the waystring formatting would also be useful in the dateconvert py program you might want to try redoing that program using string formatting in place of str(and concatenation file processing began the with reference to word-processing as an application of the string data type one critical feature of any word processing program is the ability to store and retrieve documents as files on disk in this sectionwe'll take look at file input and outputwhichas it turns outis really just another form of string processing |
19,626 | multi-line strings conceptuallya file is sequence of data that is stored in secondary memory (usually on disk drivefiles can contain any data typebut the easiest files to work with are those that contain text files of text have the advantage that they can be read and understood by humansand they are easily created and edited using general-purpose text editors and word processors in pythontext files can be very flexiblesince it is easy to convert back and forth between strings and other types you can think of text file as (possibly longstring that happens to be stored on disk of coursea typical file generally contains more than single line of text special character or sequence of characters is used to mark the end of each line there are numerous conventions for end-of-line markers python takes care of these different conventions for us and just uses the regular newline character (designated with \nto indicate line breaks let' take look at concrete example suppose you type the following lines into text editor exactly as shown herehello world goodbye when stored to fileyou get this sequence of characters hello\nworld\ \ngoodbye \ notice that the blank line becomes bare newline in the resulting file/string by the waythis is really no different than when we embed newline characters into output stringsto produce multiple lines of output with single print statement here is the example from above printed interactivelyprint("hello\nworld\ \ngoodbye \ "hello world goodbye remember if you simply evaluate string containing newline characters in the shellyou will just get the embedded newline representation back again "hello\nworld\ \ngoodbye \ 'hello\nworld\ \ngoodbye \nit' only when string is printed that the special characters affect how the string is displayed |
19,627 | sequencesstringslistsand files file processing the exact details of file-processing differ substantially among programming languagesbut virtually all languages share certain underlying file manipulation concepts firstwe need some way to associate file on disk with an object in program this process is called opening file once file has been openedit' contents can be accessed through the associated file object secondwe need set of operations that can manipulate the file object at the very leastthis includes operations that allow us to read the information from file and write new information to file typicallythe reading and writing operations for text files are similar to the operations for text-basedinteractive input and output finallywhen we are finished with fileit is closed closing file makes sure that any bookkeeping that was necessary to maintain the correspondence between the file on disk and the file object is finished up for exampleif you write information to file objectthe changes might not show up on the disk version until the file has been closed this idea of opening and closing files is closely related to how you might work with files in an application program like word processor howeverthe concepts are not exactly the same when you open file in program like microsoft wordthe file is actually read from the disk and stored into ram in programming terminologythe file is opened for reading and the contents of the file are then read into memory via file reading operations at this pointthe file is closed (again in the programming senseas you "edit the file,you are really making changes to data in memorynot the file itself the changes will not show up in the file on the disk until you tell the application to "saveit saving file also involves multi-step process firstthe original file on the disk is reopenedthis time in mode that allows it to store information--the file on disk is opened for writing doing so actually erases the old contents of the file file writing operations are then used to copy the current contents of the in-memory version into the new file on the disk from your perspectiveit appears that you have edited an existing file from the program' perspectiveyou have actually opened fileread its contents into memoryclosed the filecreated new file (having the same name)written the (modifiedcontents of memory into the new fileand closed the new file working with text files is easy in python the first step is to create file object corresponding to file on disk this is done using the open function usuallya file object is immediately assigned to variable like this open(here name is string that provides the name of the file on the disk the mode parameter is either the string "ror "wdepending on whether we intend to read from the file or write to the file for exampleto open file called "numbers datfor readingwe could use statement like the followinginfile open("numbers dat"" "now we can use the file object infile to read the contents of numbers dat from the disk python provides three related operations for reading information from file |
19,628 | read(returns the entire remaining contents of the file as single (potentially largemulti-linestring readline(returns the next line of the file that is all text up to and including the next newline character readlines(returns list of the remaining lines in the file each list item is single line including the newline character at the end here' an example program that prints the contents of file to the screen using the read operationprintfile py prints file to the screen def main()fname input("enter filename"infile open(fname," "data infile read(print(datamain(the program first prompts the user for file name and then opens the file for reading through the variable infile you could use any name for the variablei used infile to emphasize that the file was being used for input the entire contents of the file is then read as one large string and stored in the variable data printing data causes the contents to be displayed the readline operation can be used to read the next line from file successive calls to readline get successive lines from the file this is analogous to inputwhich reads characters interactively until the user hits the keyeach call to input gets another line from the user one thing to keep in mindhoweveris that the string returned by readline will always end with newline characterwhereas input discards the newline character as quick examplethis fragment of code prints out the first five lines of fileinfile open(somefile" "for in range( )line infile readline(print(line[:- ]notice the use of slicing to strip off the newline character at the end of the line since print automatically jumps to the next line ( it outputs newline)printing with the explicit newline at the end would put an extra blank line of output between the lines of the file alternativelyyou could print the whole linebut simply tell print not to add it' own newline character print(lineend="" |
19,629 | sequencesstringslistsand files one way to loop through the entire contents of file is to read in all of the file using readlines and then loop through the resulting list infile open(somefile" "for line in infile readlines()process the line here infile close(of coursea potential drawback of this approach is the fact that the file may be very largeand reading it into list all at once may take up too much ram fortunatelythere is simple alternative python treats the file itself as sequence of lines so looping through the lines of file can be done directly like thisinfile open(somefile" "for line in infileprocess the line here infile close(this is particularly handy way to process the lines of file one at time opening file for writing prepares that file to receive data if no file with the given name existsa new file will be created word of warningif file with the given name does existpython will delete it and create newempty file when writing to filemake sure you do not clobber any files you will need laterhere is an example of opening file for outputoutfile open("mydata out"" "the easiest way to write information into text file is to use the print statement with which you are already familiar to print to filewe just need to add an extra keyword parameter that specifies the fileprintfile=this behaves exactly like normal print except that the result is sent to outputfile instead of being displayed on the screen example programbatch usernames to see how all these pieces fit togetherlet' redo the username generation program our previous version created usernames interactively by having the user type in his or her name if we were setting up accounts for large number of usersthe process would probably not be done interactivelybut in batch mode in batch processingprogram input and output is done through files our new program is designed to process file of names each line of the input file will contain the first and last names of new user separated by one or more spaces the program produces an output file containing line for each generated username |
19,630 | userfile py program to create file of usernames in batch mode def main()print("this program creates file of usernames from "print("file of names "get the file names infilename input("what file are the names in"outfilename input("what file should the usernames go in"open the files infile open(infilename" "outfile open(outfilename" "process each line of the input file for line in infileget the first and last names from line firstlast line split(create the username uname (first[ ]+last[: ]lower(write it to the output file print(unamefile=outfileclose both files infile close(outfile close(print("usernames have been written to"outfilenamemain(there are couple things worth noticing in this program have two files open at the same timeone for input (infileand one for output (outfileit' not unusual for program to operate on several files simultaneously alsowhen creating the usernamei used the lower string method notice that the method is applied to the string that results from the concatenation this ensures that the username is all lower caseeven if the input names are mixed case summary this has covered important elements of the python typesstringslistsand files here is summary of the highlights |
19,631 | strings are sequences of characters string literals can be delimited with either single or double quotes strings and lists can be manipulated with the built-in sequence operations for concatenation (+)repetition (*)indexing ([])slicing ([:])and length (len() for loop can be used to iterate through the characters of stringitems in listor lines of file one way of converting numeric information into string information is to use string or list as lookup table lists are more general than strings strings are always sequences of characterswhereas lists can contain values of any type lists are mutablewhich means that items in list can be modified by assigning new values strings are represented in the computer as numeric codes ascii and unicode are compatible standards that are used for specifying the correspondence between characters and the underlying codes python provides the ord and chr functions for translating between unicode codes and characters python string and list objects include many useful built-in methods for string and list processing the process of encoding data to keep it private is called encryption there are two different kinds of encryption systemsprivate key and public key program input and output often involve string processing python provides numerous operators for converting back and forth between numbers and strings the string formatting method (formatis particularly useful for producing nicely formatted output text files are multi-line strings stored in secondary memory file may be opened for reading or writing when opened for writingthe existing contents of the file are erased python provides three file reading methodsread()readline(and readlines(it is also possible to iterate through the lines of file with for loop data is written to file using the print function when processing is finisheda file should be closed exercises review questions true/false python string literal is always enclosed in double quotes the last character of string is at position len( )- |
19,632 | string always contains single line of text in python " " is " python lists are mutablebut strings are not ascii is standard for representing characters using numeric codes the split method breaks string into list of substringsand join does the opposite substitution cipher is good way to keep sensitive information secure the add method can be used to add an item to the end of list the process of associating file with an object in program is called "readingthe file multiple choice accessing single character out of string is calledaslicing bconcatenation cassignment dindexing which of the following is the same as [ :- ]as[- bs[:cs[:len( )- ds[ :len( ) what function gives the unicode value of characteraord bascii cchr deval which of the following can not be used to convert string of digits into numberaint bfloat cstr deval successor to ascii that includes characters from (nearlyall written languages is atelli bascii+cunicode diso which string method converts all the characters of string to upper caseacapitalize bcapwords cuppercase dupper the string "slotsthat are filled in by the format method are marked byabc[ { which of the following is not file reading method in pythonaread breadline creadall dreadlines the term for program that does its / with files is afile-oriented bmulti-line cbatch dlame before reading or writing to filea file object must be created via aopen bcreate cfile dfolder |
19,633 | discussion given the initial statementss "spams "ni!show the result of evaluating each of the following string expressions ( "the knights who says ( (cs [ (ds [ : (es [ [: (fs [- (gs upper((hs upper(ljust( given the same initial statements as in the previous problemshow python expression that could construct each of the following results by performing string operations on and ( "ni( "ni!spamni!( "spam nispam nispam ni!( "spam( ["sp"," "( "spm show the output that would be generated by each of the following program fragments(afor ch in "aardvark"print(ch(bfor in "now is the winter of our discontent split()print( (cfor in "mississippisplit(" ")print(wend="(dmsg "for in "secretsplit(" ")msg msg print(msg |
19,634 | (emsg "for ch in "secret"msg msg chr(ord(ch)+ print(msg show the string that would result from each of the following string formatting operations if the operation is not legalexplain why ( "looks like { and { for breakfastformat("eggs""spam"( "there is { { { { }format( ,"spam" "you"( "hello { }format("susan""computewell"( "{ : { : }format( ( "{ { }format( ( "time left { : }:{ : }format( ( "{ : }format(" " explain why public key encryption is more useful for securing communications on the internet than private (sharedkey encryption programming exercises as discussed in the string formatting could be used to simplify the dateconvert py program go back and redo this program making use of the string-formatting method certain cs professor gives -point quizzes that are graded on the scale - - - - - write program that accepts quiz score as an input and prints out the corresponding grade certain cs professor gives -point exams that are graded on the scale - : - : - : - : < : write program that accepts an exam score as input and prints out the corresponding grade an acronym is word formed by taking the first letters of the words in phrase and making word from them for exampleram is an acronym for "random access memory write program that allows the user to type in phrase and then outputs the acronym for that phrase notethe acronym should be all uppercaseeven if the words in the phrase are not capitalized numerologists claim to be able to determine person' character traits based on the "numeric valueof name the value of name is determined by summing up the values of the letters of the name where 'ais 'bis 'cis etc up to 'zbeing for examplethe name "zellewould have the value (which happens to be very auspicious numberby the waywrite program that calculates the numeric value of single name provided as input |
19,635 | expand your solution to the previous problem to allow the calculation of complete name such as "john marvin zelleor "john jacob jingleheimer smith the total value is just the sum of the numeric values of all the names caesar cipher is simple substitution cipher based on the idea of shifting each letter of the plaintext message fixed number (called the keyof positions in the alphabet for exampleif the key value is the word "sourpusswould be encoded as "uqwtrwuu the original message can be recovered by "reencodingit using the negative of the key write program that can encode and decode caesar ciphers the input to the program will be string of plaintext and the value of the key the output will be an encoded message where each character in the original message is replaced by shifting it key characters in the unicode character set for exampleif ch is character in the string and key is the amount to shiftthen the character that replaces ch can be calculated aschr(ord(chkey one problem with the previous exercise is that it does not deal with the case when we "drop off the endof the alphabet true caesar cipher does the shifting in circular fashion where the next character after "zis "amodify your solution to the previous problem to make it circular you may assume that the input consists only of letters and spaces hintmake string containing all the characters of your alphabet and use positions in this string as your code you do not have to shift "zinto "ajust make sure that you use circular shift over the entire sequence of characters in your alphabet string write program that counts the number of words in sentence entered by the user write program that calculates the average word length in sentence entered by the user write an improved version of the chaos program from that allows user to input two initial values and the number of iterations and then prints nicely formatted table showing how the values change over time for exampleif the starting values were and with iterationsthe table might look like thisindex |
19,636 | write an improved version of the future value program from your program will prompt the user for the amount of the investmentthe annualized interest rateand the number of years of the investment the program will then output nicely formatted table that tracks the value of the investment year by year your output might look something like thisyear value $ $ $ $ $ $ $ $ redo any of the previous programming problems to make them batch oriented (using text files for input and output word count common utility on unix/linux systems is small program called "wc this program analyzes file to determine the number of lineswordsand characters contained therein write your own version of wc the program should accept file name as input and then print three numbers showing the count of lineswordsand characters in the file write program to plot horizontal bar chart of student exam scores your program should get input from file the first line of the file contains the count of the number of students in the fileand each subsequent line contains student' last name followed by score in the range to your program should draw horizontal rectangle for each student where the length of the bar represents the student' score the bars should all line up on their lefthand edges hintuse the number of students to determine the size of the window and its coordinates bonuslabel the bars at the left end with the student name computewell dibblebit jones smith write program to draw quiz score histogram your program should read data from file each line of the file contains number in the range - your program must count the number of occurrences of each score and then draw vertical bar chart with bar for each possible score ( - with height corresponding to the count of that score for exampleif students got an then the height of the bar for should be hintuse list that stores the count for each possible score |
19,637 | |
19,638 | defining functions objectives to understand why programmers divide programs up into sets of cooperating functions to be able to define new functions in python to understand the details of function calls and parameter passing in python to write programs that use functions to reduce code duplication and increase program modularity the function of functions the programs that we have written so far comprise single functionusually called main we have also been using pre-written functions and methods including built-in python functions ( abseval)functions and methods from the python standard libraries ( math sqrt)and methods from the graphics module ( mypoint getx()functions are an important tool for building sophisticated programs this covers the whys and hows of designing your own functions to make your programs easier to write and understand in we looked at graphic solution to the future value problem recallthis program makes use of the graphics library to draw bar chart showing the growth of an investment here is the program as we left itfutval_graph py from graphics import def main()introduction print("this program plots the growth of -year investment " |
19,639 | get principal and interest rate principal eval(input("enter the initial principal")apr eval(input("enter the annualized interest rate")create graphics window with labels on left edge win graphwin("investment growth chart" win setbackground("white"win setcoords(- ,- text(point(- ) 'draw(wintext(point(- ) 'draw(wintext(point(- ) 'draw(wintext(point(- ) 'draw(wintext(point(- )' 'draw(windraw bar for initial principal bar rectangle(point( )point( principal)bar setfill("green"bar setwidth( bar draw(windraw bar for each subsequent year for year in range( )principal principal ( aprbar rectangle(point(year )point(year+ principal)bar setfill("green"bar setwidth( bar draw(wininput("press to quit "win close(main(this is certainly workable programbut there is nagging issue of program style that really should be addressed notice that this program draws bars in two different places the initial bar is drawn just before the loopand the subsequent bars are drawn inside of the loop having similar code like this in two places has some drawbacks obviouslyone issue is having to write the code twice more subtle problem is that the code has to be maintained in two different places should we decide to change the color or other facets of the barswe would have to make sure these changes occur in both places failing to keep related parts of the code in sync is common problem in program maintenance functions can be used to reduce code duplication and to make programs more understandable |
19,640 | and easier to maintain before fixing up the future value programlet' take look at what functions have to offer functionsinformally you can think of function as subprogram-- small program inside of program the basic idea of function is that we write sequence of statements and give that sequence name the instructions can then be executed at any point in the program by referring to the function name the part of the program that creates function is called function definition when function is subsequently used in programwe say that the definition is called or invoked single function definition may be called at many different points of program let' take concrete example suppose you want to write program that prints out the lyrics to the "happy birthdaysong the standard lyrics look like this happy birthday to youhappy birthday to youhappy birthdaydear happy birthday to youwe're going to play with this example in the interactive python environment you might want to fire up python and try some of this out yourself simple approach to this problem is to use four print statements here' an interactive session that creates program for singing "happy birthdayto fred def main()print("happy birthday to you!"print("happy birthday to you!"print("happy birthdaydear fred "print("happy birthday to you!"we can then run this program to get our lyrics main(happy birthday to youhappy birthday to youhappy birthdaydear fred happy birthday to youobviouslythere is some duplicated code in this program for such simple programthat' not big dealbut even here it' bit annoying to keep retyping the same line let' introduce function that prints the lyrics of the firstsecondand fourth lines def happy()print("happy birthday to you!" |
19,641 | defining functions we have defined new function called happy here is an example of what it doeshappy(happy birthday to youinvoking the happy command causes python to print line of the song now we can redo the verse for fred using happy let' call our new version singfred def singfred()happy(happy(print("happy birthdaydear fred "happy(this version required much less typingthanks to the happy command let' try printing the lyrics for fred just to make sure it works singfred(happy birthday to youhappy birthday to youhappy birthdaydear fred happy birthday to youso farso good now suppose that it' also lucy' birthdayand we want to sing verse for fred followed by verse for lucy we've already got the verse for fredwe can prepare one for lucy as well def singlucy()happy(happy(print("happy birthdaydear lucy "happy(now we can write main program that sings to both fred and lucy def main()singfred(print(singlucy(the bare print between the two function calls puts space between the verses in our output and here' the final product in actionmain(happy birthday to youhappy birthday to you |
19,642 | happy birthdaydear fred happy birthday to youhappy birthday to youhappy birthday to youhappy birthdaydear lucy happy birthday to youwell nowthat certainly seems to workand we've removed some of the duplication by defining the happy function howeversomething still doesn' feel quite right we have two functionssingfred and singlucythat are almost identical following this approachadding verse for elmer would have us create singelmer function that looks just like those for fred and lucy can' we do something about the proliferation of versesnotice that the only difference between singfred and singlucy is the name at the end of the third print statement the verses are exactly the same except for this one changing part we can collapse these two functions together by using parameter let' write generic function called sing def sing(person)happy(happy(print("happy birthdaydear"person "happy(this function makes use of parameter named person parameter is variable that is initialized when the function is called we can use the sing function to print verse for either fred or lucy we just need to supply the name as parameter when we invoke the function sing("fred"happy birthday to youhappy birthday to youhappy birthdaydear fred happy birthday to yousing("lucy"happy birthday to youhappy birthday to youhappy birthdaydear lucy happy birthday to youlet' finish with program that sings to all three of our birthday people def main()sing("fred"print( |
19,643 | sing("lucy"print(sing("elmer"it doesn' get much easier than that here is the complete program as module file happy py def happy()print("happy birthday to you!"def sing(person)happy(happy(print("happy birthdaydear"person "happy(def main()sing("fred"print(sing("lucy"print(sing("elmer"main( future value with function now that you've seen how defining functions can help solve the code duplication problemlet' return to the future value graph rememberthe problem is that bars of the graph are drawn at two different places in the program the code just before the loop looks like thisdraw bar for initial principal bar rectangle(point( )point( principal)bar setfill("green"bar setwidth( bar draw(winand the code inside of the loop is as follows bar rectangle(point(year )point(year+ principal)bar setfill("green" |
19,644 | bar setwidth( bar draw(winlet' try to combine these two into single function that draws bar on the screen in order to draw the barwe need some information specificallywe need to know what year the bar will be forhow tall the bar will beand what window the bar will be drawn in these three values will be supplied as parameters for the function here' the function definitiondef drawbar(windowyearheight)draw bar in window for given year with given height bar rectangle(point(year )point(year+ height)bar setfill("green"bar setwidth( bar draw(windowto use this functionwe just need to supply values for the three parameters for exampleif win is graphwinwe can draw bar for year and principal of $ , by invoking drawbar like thisdrawbar(win incorporating the drawbar functionhere is the latest version of our future value programfutval_graph py from graphics import def drawbar(windowyearheight)draw bar in window starting at year with given height bar rectangle(point(year )point(year+ height)bar setfill("green"bar setwidth( bar draw(windowdef main()introduction print("this program plots the growth of -year investment "get principal and interest rate principal eval(input("enter the initial principal")apr eval(input("enter the annualized interest rate")create graphics window with labels on left edge win graphwin("investment growth chart" win setbackground("white"win setcoords(- ,- text(point(- ) 'draw(win |
19,645 | text(point(- ) 'draw(wintext(point(- ) 'draw(wintext(point(- ) 'draw(wintext(point(- )' 'draw(windrawbar(win principalfor year in range( )principal principal ( aprdrawbar(winyearprincipalinput("press to quit "win close(main(you can see how drawbar has eliminated the duplicated code should we wish to change the appearance of the bars in the graphwe only need to change the code in one spotthe definition of drawbar don' worry yet if you don' understand every detail of this example you still have some things to learn about functions functions and parametersthe exciting details you may be wondering about the choice of parameters for the drawbar function obviouslythe year for which bar is being drawn and the height of the bar are the changeable parts in the drawing of bar but why is window also parameter to this functionafter allwe will be drawing all of the bars in the same windowit doesn' seem to change the reason for making window parameter has to do with the scope of variables in function definitions scope refers to the places in program where given variable may be referenced remember each function is its own little subprogram the variables used inside of one function are local to that functioneven if they happen to have the same name as variables that appear inside of another function the only way for function to see variable from another function is for that variable to be passed as parameter since the graphwin (assigned to the variable winis created inside of mainit is not directly accessible in drawbar howeverthe window parameter in drawbar gets assigned the value of win from main when drawbar is called to see how this happenswe need to take more detailed look at the function invocation process function definition looks like this def () technicallyit is possible to reference variable from function that is nested inside another functionbut function nesting is beyond the scope of this discussion |
19,646 | the name of the function must be an identifierand formal-parameters is (possibly emptylist of variable names (also identifiersthe formal parameterslike all variables used in the functionare only accessible in the body of the function variables with identical names elsewhere in the program are distinct from the formal parameters and variables inside of the function body function is called by using its name followed by list of actual parameters or arguments (when python comes to function callit initiates four-step process the calling program suspends execution at the point of the call the formal parameters of the function get assigned the values supplied by the actual parameters in the call the body of the function is executed control returns to the point just after where the function was called returning to the happy birthday examplelet' trace through the singing of two verses here is part of the body from mainsing("fred"print(sing("lucy"when python gets to sing("fred")execution of main is temporarily suspended at this pointpython looks up the definition of sing and sees that it has single formal parameterperson the formal parameter is assigned the value of the actualso it is as if we had executed this statementperson "freda snapshot of this situation is shown in figure notice the variable person inside of sing has just been initialized def sing(person)def main()happy(sing("fred"person "fredhappy(print(print("happy birthdaydear"person "sing("lucy"happy(person"fredfigure illustration of control transferring to sing at this pointpython begins executing the body of sing the first statement is another function callthis one to happy python suspends execution of sing and transfers control to the called |
19,647 | def happy()def sing(person)def main()print("happy birthday to you!"happy(sing("fred"person "fredhappy(print(print("happy birthdaydear"person "sing("lucy"happy(person"fredfigure snapshot of completed call to happy function the body of happy consists of single print this statement is executedand then control returns to where it left off in sing figure shows snapshot of the execution so far execution continues in this manner with python making two more side trips back to happy to complete the execution of sing when python gets to the end of singcontrol then returns to main and continues immediately after the function call figure shows where we are at that point notice that the person variable in sing has disappeared the memory occupied by local function variables is reclaimed when the function finishes local variables do not retain any values from one function execution to the next def main()sing("fred"print(sing("lucy"def sing(person)happy(happy(print("happy birthdaydear"person "happy(figure snapshot of completed call to sing the next statement to execute is the bare print statement in main this produces blank line in the output then python encounters another call to sing as beforecontrol transfers to the function definition this time the formal parameter is "lucyfigure shows the situation as sing begins to execute for the second time def sing(person)def main()happy(sing("fred"yhappy( print( print("happy birthdaydear"person "sing("lucy"person happy(person"lucyfigure snapshot of second call to sing now we'll fast forward to the end the function body of sing is executed for lucy (with three side trips through happyand control returns to main just after the point of the function call now we have reached the bottom of our code fragmentas illustrated by figure these three |
19,648 | statements in main have caused sing to execute twice and happy to execute six times overallnine total lines of output were generated def main()sing("fred"print(sing("lucy"def sing(person)happy(happy(print("happy birthdaydear"person "happy(figure completion of second call to sing hopefully you're getting the hang of how function calls actually work one point that this example did not address is the use of multiple parameters usually when function definition has several parametersthe actual parameters are matched up with the formal parameters by position the first actual parameter is assigned to the first formal parameterthe second actual is assigned to the second formaletc it' possible to modify this behavior using keyword parameterswhich are matched up by name ( end="in call to printhoweverwe will rely on positional matching for all of our example functions as an examplelook again at the use of the drawbar function from the future value program here is the call to draw the initial bardrawbar(win principalwhen python transfers control to drawbarthese parameters are matched up to the formal parameters in the function heading def drawbar(windowyearheight)the net effect is as if the function body had been prefaced with three assignment statements window win year height principal you must always be careful when calling function that you get the actual parameters in the correct order to match the function definition getting results from function you have seen that parameter passing provides mechanism for initializing the variables in function in wayparameters act as inputs to function we can call function many times and get different results by changing the input parameters oftentimes we also want to get information back out of function |
19,649 | defining functions functions that return values one way to get information from function is by having it return value to the caller you have already seen numerous examples of this type of function for exampleconsider this call to the sqrt function from the math librarydiscrt math sqrt( * * *chere the value of * * * is the actual parameter of math sqrt this function call occurs on the right side of an assignment statementthat means it is an expression the math sqrt function must somehow produce value that is then assigned to the variable discrt technicallywe say that sqrt returns the square root of its argument it' very easy to write functions that return values here' an example value-returning function that does the opposite of sqrtit returns the square of its argumentdef square( )return the body of this function consists of single return statement when python encounters returnit exits the function and returns control to the point where the function was called in additionthe value(sprovided in the return statement are sent back to the caller as an expression result we can use our square function any place that an expression would be legal here are some interactive examplessquare( print(square( ) square(xprint( print(square(xsquare( ) let' use the square function to write another function that finds the distance between two points given two points ( and ( )the distance between them is calculated from the pythagorean theorem as ( ) ( ) here is python function to compute the distance between two point objectsdef distance( )dist math sqrt(square( getx( getx()square( gety( gety()return dist using the distance functionwe can augment the interactive triangle program from to calculate the perimeter of the triangle here' the complete program |
19,650 | programtriangle py import math from graphics import def square( )return def distance( )dist math sqrt(square( getx( getx()square( gety( gety())return dist def main()win graphwin("draw triangle"win setcoords( message text(point( )"click on three points"message draw(winget and draw three vertices of triangle win getmouse( draw(winp win getmouse( draw(winp win getmouse( draw(winuse polygon object to draw the triangle triangle polygon( , , triangle setfill("peachpuff"triangle setoutline("cyan"triangle draw(wincalculate the perimeter of the triangle perim distance( , distance( , distance( , message settext("the perimeter is{ : }format(perim)wait for another click to exit win getmouse(win close(main( |
19,651 | defining functions you can see how distance is called three times in one line to compute the perimeter of the triangle using function here saves quite bit of tedious coding sometimes function needs to return more than one value this can be done by simply listing more than one expression in the return statement as silly examplehere is function that computes both the sum and the difference of two numbers def sumdiff( , )sum diff return sumdiff as you can seethis return hands back two values when calling this functionwe would place it in simultaneous assignment num num eval(input("please enter two numbers (num num ")sd sumdiff(num num print("the sum is" "and the difference is"das with parameterswhen multiple values are returned from functionthey are assigned to variables by position in this examples will get the first value listed in the return (sum)and will get the second value (diffthat' just about all there is to know about value-returning functions in python there is one "gotchato warn you about technicallyall functions in python return valueregardless of whether or not the function actually contains return statement functions without return always hand back special objectdenoted none this object is often used as sort of default value for variables that don' currently hold anything useful common mistake that new (and not-so-newprogrammers make is writing what should be value-returning function but forgetting to include return statement at the end suppose we forget to include the return statement at the end of the distance function def distance( )dist math sqrt(square( getx( getx()square( gety( gety())running the revised triangle program with this version of distance generates this python error messagetraceback (most recent call last)file "triangle py"line in main(file "triangle py"line in main perim distance( , distance( , distance( , typeerrorunsupported operand type(sfor +'nonetypeand 'nonetypethe problem here is that this version of distance does not return numberit always hands back the value none addition is not defined for none (which has the special type nonetype)and so python complains if your value-returning functions are producing strange error messages involving nonecheck to make sure you remembered to include the return |
19,652 | functions that modify parameters return values are the main way to send information from function back to the part of the program that called the function in some casesfunctions can also communicate back to the calling program by making changes to the function parameters understanding when and how this is possible requires the mastery of some subtle details about how assignment works in python and the effect this has on the relationship between the actual and formal parameters used in function call let' start with simple example suppose you are writing program that manages bank accounts or investments one of the common tasks that must be performed is to accumulate interest on an account (as we did in the future value programwe might consider writing function that automatically adds the interest to the account balance here is first attempt at such functionaddinterest py def addinterest(balancerate)newbalance balance ( +ratebalance newbalance the intent of this function is to set the balance of the account to value that has been updated by the amount of interest let' try out our function by writing very small test program def test()amount rate addinterest(amountrateprint(amountwhat to you think this program will printour intent is that should be added to amountgiving result of here' what actually happensaddinterest test( as you can seeamount is unchangedwhat has gone wrongactuallynothing has gone wrong if you consider carefully what we have discussed so far regarding functions and parametersyou will see that this is exactly the result that we should expect let' trace the execution of this example to see what happens the first two lines of the test function create two local variables called amount and rate which are given the initial values of and respectively nextcontrol transfers to the addinterest function the formal parameters balance and rate are assigned the values from the actual parameters amount and rate remembereven though the name rate appears in both functionsthese are two separate variables the situation as addinterest begins to execute is shown in figure notice that the assignment of parameters causes the variables balance and rate in addinterest to refer to the values of the actual parameters |
19,653 | oun def addinterest(balancerate)def test()=am nce newbalance balance ( ratea amount ba = balance newbalance rate rat addinterest(amount,rateprint(amountbalance amount rate rate figure transfer of control to addinterest executing the first line of addinterest creates new variable newbalance now comes the key step the next statement in addinterest assigns balance to have the same value as newbalance the result is shown in figure notice that balance now refers to the same value as newbalancebut this had no effect on amount in the test function unt def addinterest(balancerate)amo def test()cen newbalance balance ( ratea amount ate bal = balance newbalance rate rat addinterest(amount,rateprint(amountbalance amount rate rate newbalance figure assignment of balance at this pointexecution of addinterest has completed and control returns to test the local variables (including parametersin addinterest go awaybut amount and rate in the test function still refer to the initial values of and respectively of coursethe program prints the value of amount as to summarize the situationthe formal parameters of function only receive the values of the actual parameters the function does not have any access to the variable that holds the actual parameterthereforeassigning new value to formal parameter has no effect on the variable that contains the actual parameter in programming language parlancepython is said to pass all |
19,654 | parameters by value some programming languages ( +and ada)do allow variables themselves to be sent as parameters to function such mechanism is called passing parameters by reference when variable is passed by referenceassigning new value to the formal parameter actually changes the value of the parameter variable in the calling program since python does not allow passing parameters by referencean obvious alternative is to change our addinterest function so that it returns the newbalance this value can then be used to update the amount in the test function here' working versionaddinterest py def addinterest(balancerate)newbalance balance ( +ratereturn newbalance def test()amount rate amount addinterest(amountrateprint(amounttest(you should easily be able to trace through the execution of this program to see how we get this output addinterest test( now suppose instead of looking at single accountwe are writing program that deals with many bank accounts we could store the account balances in python list it would be nice to have an addinterest function that adds the accrued interest to all of the balances in the list if balances is list of account balanceswe can update the first amount in the list (the one at index with line of code like thisbalances[ balances[ ( raterememberthis works because lists are mutable this line of code essentially says"multiply the value in the th position of the list by ( +rateand store the result back into the th position of the list of coursea very similar line of code would work to update the balance of the next location in the listwe just replace the with balances[ balances[ ( ratea more general way of updating all the balances in list is to use loop that goes through positions length here is program that implements this idea |
19,655 | addinterest py def addinterest(balancesrate)for in range(len(balances))balances[ibalances[ ( +ratedef test()amounts [ rate addinterest(amountsrateprint(amountstest(take moment to study this program the test function starts by setting amounts to be list of four values then the addinterest function is called sending amounts as the first parameter after the function callthe value of amounts is printed out what do you expect to seelet' run this little program and see what happens addinterest test([ isn' that interestingin this examplethe function seems to change the value of the amounts variable but just told you that python passes parameters by valueso the variable itself (amountscan' be changed by the function so what' going on herethe first two lines of test create the variables amounts and ratesand then control transfers to the addinterest function the situation at this point is depicted in figure notice that the def test()amounts [ , , , rate addinterest(amounts,rateprint(amountsdef addinterest(balancesrate)for in range(len(balances))balances[ibalances[ ( +raterate rate balances amounts figure transfer of list parameter to addinterest |
19,656 | value of the variable amounts is now list object that itself contains four int values it is this list object that gets passed to addinterest and is therefore also the value of balances next addinterest executes the loop goes through each index in the range length and updates that item in balances the result is shown in figure you'll notice in the diagram def test()amounts [ , , , rate addinterest(amounts,rateprint(amountsdef addinterest(balancesrate)for in range(len(balances))balances[ibalances[ ( +raterate rate balances amounts figure list modified in addinterest that left the old values ( just hanging around did this to emphasize that the numbers in the value boxes have not changed instead what has happened is that new values were createdand the assignments into the list caused it to refer to the new values the old values will actually get cleaned up when python does garbage collection it should be clear now why the list version of the addinterest program produces the answer that it does when addinterest terminatesthe list stored in amounts now contains the new balancesand that is what gets printed notice that the variable amounts was never changed it still refers to the same list that it did before the call to addinterest what has happened is that the state of that list has changedand this change is visible back in the calling program now you really know everything there is to know about how python passes parameters to functions parameters are always passed by value howeverif the value of the variable is mutable object (like list or graphics object)then changes to the state of the object will be visible to the calling program this latter situation is another example of the aliasing issue discussed in functions and program structure so farwe have been discussing functions as mechanism for reducing code duplicationthus shortening and simplifying our programs surprisinglyfunctions are often used even when doing so actually makes program longer second reason for using functions is to make programs more |
19,657 | modular as the algorithms that you design get more complexit gets more and more difficult to make sense out of programs humans are pretty good at keeping track of eight to ten things at time when presented with an algorithm that is hundreds of lines longeven the best programmers will throw up their hands in bewilderment one way to deal with this complexity is to break an algorithm into smaller subprogramseach of which makes sense on its own 'll have lot more to say about this later when we discuss program design in for nowwe'll just take look at an example let' return to the future value problem one more time here is the main program as we left itdef main()introduction print("this program plots the growth of -year investment "get principal and interest rate principal eval(input("enter the initial principal")apr eval(input("enter the annualized interest rate")create graphics window with labels on left edge win graphwin("investment growth chart" win setbackground("white"win setcoords(- ,- text(point(- ) 'draw(wintext(point(- ) 'draw(wintext(point(- ) 'draw(wintext(point(- ) 'draw(wintext(point(- )' 'draw(windraw bar for initial principal drawbar(win principaldraw bar for each subsequent year for year in range( )principal principal ( aprdrawbar(winyearprincipalinput("press to quit "win close(main(although we have already shortened this algorithm through the use of the drawbar functionit is still long enough to make reading through it awkward the comments help to explain things |
19,658 | but--not to put too fine point on it--this function is just too long one way to make the program more readable is to move some of the details into separate function for examplethere are eight lines in the middle that simply create the window where the chart will be drawn we could put these steps into value returning function def createlabeledwindow()returns graphwin with title and labels drawn window graphwin("investment growth chart" window setbackground("white"window setcoords(- ,- text(point(- ) 'draw(windowtext(point(- ) 'draw(windowtext(point(- ) 'draw(windowtext(point(- ) 'draw(windowtext(point(- )' 'draw(windowreturn window as its name impliesthis function takes care of all the nitty-gritty details of drawing the initial window it is self-contained entity that performs this one well-defined task using our new functionthe main algorithm seems much simpler def main()print("this program plots the growth of -year investment "principal input("enter the initial principal"apr input("enter the annualized interest rate"win createlabeledwindow(drawbar(win principalfor year in range( )principal principal ( aprdrawbar(winyearprincipalinput("press to quit "win close(notice that have removed the commentsthe intent of the algorithm is now clear with suitably named functionsthe code has become nearly self-documenting here is the final version of our future value programfutval_graph py from graphics import |
19,659 | def createlabeledwindow()window graphwin("investment growth chart" window setbackground("white"window setcoords(- ,- text(point(- ) 'draw(windowtext(point(- ) 'draw(windowtext(point(- ) 'draw(windowtext(point(- ) 'draw(windowtext(point(- )' 'draw(windowreturn window def drawbar(windowyearheight)bar rectangle(point(year )point(year+ height)bar setfill("green"bar setwidth( bar draw(windowdef main()print("this program plots the growth of year investment "principal eval(input("enter the initial principal")apr eval(input("enter the annualized interest rate")win createlabeledwindow(drawbar(win principalfor year in range( )principal principal ( aprdrawbar(winyearprincipalinput("press to quit "win close(main(although this version is longer than the previous versionexperienced programmers would find it much easier to understand as you get used to reading and writing functionsyou too will learn to appreciate the elegance of more modular code summary function is kind of subprogram programmers use functions to reduce code duplication and to help structure or modularize programs once function is definedit may be called |
19,660 | multiple times from many different places in program parameters allow functions to have changeable parts the parameters appearing in the function definition are called formal parametersand the expressions appearing in function call are known as actual parameters call to function initiates four step process the calling program is suspended the values of actual parameters are assigned to the formal parameters the body of the function is executed control returns immediately following the function call in the calling program the scope of variable is the area of the program where it may be referenced formal parameters and other variables inside function definitions are local to the function local variables are distinct from variables of the same name that may be used elsewhere in the program functions can communicate information back to the caller through return values python functions may return multiple values value returning functions should generally be called from inside of an expression functions that don' explicitly return value return the special object none python passes parameters by value if the value being passed is mutable objectthen changes made to the object may be visible to the caller exercises review questions true/false programmers rarely define their own functions function may only be called at one place in program information can be passed into function through parameters every python function returns some value in pythonsome parameters are passed by reference in pythona function can return only one value python functions can never modify parameter one reason to use functions is to reduce code duplication variables defined in function are local to that function it' bad idea to define new functions if it makes program longer |
19,661 | multiple choice the part of program that uses function is called the auser bcaller ccallee dstatement python function definition begins with adef bdefine cfunction ddefun function can send output back to the program with (nareturn bprint cassignment dsase formal and actual parameters are matched up by aname bposition cid dinterests which of the following is not step in the function calling processathe calling program suspends bthe formal parameters are assigned the value of the actual parameters cthe body of the function executes dcontrol returns to the point just before the function was called in pythonactual parameters are passed to functions aby value bby reference cat random dby networking which of the following is not reason to use functionsato reduce code duplication bto make program more modular cto make program more self-documenting dto demonstrate intellectual superiority if function returns valueit should generally be called from aan expression ba different program cmain da cell phone function with no return statement returns anothing bits parameters cits variables dnone function can modify the value of an actual parameter only if it' amutable ba list cpassed by reference da variable discussion in your own wordsdescribe the two motivations for defining functions in your programs we have been thinking about computer programs as sequences of instructions where the computer methodically executes one instruction and then moves on to the next one do programs that contain functions fit this modelexplain your answer |
19,662 | parameters are an important concept in defining functions (awhat is the purpose of parameters(bwhat is the difference between formal parameter and an actual parameter(cin what ways are parameters similar to and different from ordinary variables functions can be thought of as miniature (sub)programs inside of other programs like any other programwe can think of functions as having input and output to communicate with the main program (ahow does program provide "inputto one of its functions(bhow does function provide "outputto the program consider this very simple functiondef cube( )answer return answer (awhat does this function do(bshow how program could use this function to print the value of assuming is variable (chere is fragment of program that uses this functionanswer result cube( print(answerresultthe output from this fragment is explain why the output is not even though cube seems to change the value of answer to programming exercises write program to print the lyrics of the song "old macdonald your program should print the lyrics for five different animalssimilar to the example verse below old macdonald had farmee-ighee-ighohand on that farm he had cowee-ighee-ighohwith moomoo here and moomoo there here moothere mooeverywhere moomoo old macdonald had farmee-ighee-ighoh write program to print the lyrics for ten verses of "the ants go marching couple of sample verses are given below you may choose your own activity for the little one in each versebut be sure to choose something that makes the rhyme work (or almost work |
19,663 | the ants go marching one by onehurrahhurrahthe ants go marching one by onehurrahhurrahthe ants go marching one by onethe little one stops to suck his thumband they all go marching down in the ground to get out of the rain boomboomboomthe ants go marching two by twohurrahhurrahthe ants go marching two by twohurrahhurrahthe ants go marching two by twothe little one stops to tie his shoeand they all go marching down in the ground to get out of the rain boomboomboom write definitions for these functionsspherearea(radiusreturns the surface area of sphere having the given radius spherevolume(radiusreturns the volume of sphere having the given radius use your functions to solve programming exercise from write definitions for the following two functionssumn(nreturns the sum of the first natural numbers sumncubes(nreturns the sum of the cubes of the first natural numbers then use these functions in program that prompts user for and prints out the sum of the first natural numbers and the sum of the cubes of the first natural numbers redo programming exercise from use two functions--one to compute the area of pizzaand one to compute cost per square inch write function that computes the area of triangle given the length of its three sides as parameters (see programming exercise from use your function to augment triangle py so that it also displays the area of the triangle write function to compute the nth fibonacci number use your function to solve programming exercise from solve programming exercise from using function nextguess(guessxthat returns the next guess |
19,664 | do programming exercise from using function grade(scorethat returns the letter grade for score do programming exercise from using function acronym(phrasethat returns an acronym for phrase supplied as string write and test function to meet this specification squareeach(numsnums is list of numbers modifies the list by squaring each entry write and test function to meet this specification sumlist(numsnums is list of numbers returns the sum of the numbers in the list write and test function to meet this specification tonumbers(strliststrlist is list of stringseach of which represents number modifies each entry in the list by converting it to number use the functions from the previous three problems to implement program that computes the sum of the squares of numbers read from file your program should prompt for file name and print out the sum of the squares of the values in the file hintuse readlines( write and test function to meet this specification drawface(centersizewincenter is pointsize is an intand win is graphwin draws simple face of the given size in win your function can draw simple smiley (or grimface demonstrate the function by writing program that draws several faces of varying size in single window write function to meet this specification moveto(shapenewcentershape is graphics object that supports the getcenter method and newcenter is point moves shape so that newcenter is its center use your function to write program that draws circle and then allows the user to click the window times each time the user clicksthe circle is moved where the user clicked |
19,665 | defining functions |
19,666 | decision structures objectives to understand the programming pattern simple decision and its implementation using python if statement to understand the programming pattern two-way decision and its implementation using python if-else statement to understand the programming pattern multi-way decision and its implementation using python if-elif-else statement to understand the idea of exception handling and be able to write simple exception handling code that catches standard python run-time errors to understand the concept of boolean expressions and the bool data type to be able to readwriteand implement algorithms that employ decision structuresincluding those that employ sequences of decisions and nested decision structures simple decisions so farwe have mostly viewed computer programs as sequences of instructions that are followed one after the other sequencing is fundamental concept of programmingbut alone it is not sufficient to solve every problem often it is necessary to alter the sequential flow of program to suit the needs of particular situation this is done with special statements known as control structures in this we'll take look at decision structureswhich are statements that allow program to execute different sequences of instructions for different caseseffectively allowing the program to "choosean appropriate course of action |
19,667 | decision structures exampletemperature warnings let' start by getting the computer to make simple decision for an easy examplewe'll return to the celsius to fahrenheit temperature conversion program from rememberthis was written by susan computewell to help her figure out how to dress each morning in europe here is the program as we left itconvert py program to convert celsius temps to fahrenheit bysusan computewell def main()celsius eval(input("what is the celsius temperature")fahrenheit / celsius print("the temperature is"fahrenheit"degrees fahrenheit "main(this is fine program as far as it goesbut we want to enhance it susan computewell is not morning personand even though she has program to convert the temperaturessometimes she does not pay very close attention to the results our enhancement to the program will ensure that when the temperatures are extremethe program prints out suitable warning so that susan takes notice the first step is to fully specify the enhancement an extreme temperature is either quite hot or quite cold let' say that any temperature over degrees fahrenheit deserves heat warningand temperature under degrees warrants cold warning with this specification in mindwe can design an enhanced algorithm input the temperature in degrees celsius (call it celsiuscalculate fahrenheit as / celsius output fahrenheit if fahrenheit print heat warning if fahrenheit print cold warning this new design has two simple decisions at the end the indentation indicates that step should be performed only if the condition listed in the previous line is met the idea here is that the decision introduces an alternative flow of control through the program the exact set of steps taken by the algorithm will depend on the value of fahrenheit figure is flowchart showing the possible paths that can be taken through the algorithm the diamond boxes show conditional decisions if the condition is falsecontrol passes to the next statement in the sequence (the one belowif the condition holdshowevercontrol transfers to the instructions in the box to the right once these instructions are donecontrol then passes to the next statement |
19,668 | input celsius temperature farenheit / celsius print fahrenheit fahrenheit no fahrenheit no yes print heat warning yes print cold warning figure flowchart of temperature conversion program with warnings here is how the new design translates into python codeconvert py program to convert celsius temps to fahrenheit this version issues heat and cold warnings def main()celsius eval(input("what is the celsius temperature")fahrenheit / celsius print("the temperature is"fahrenheit"degrees fahrenheit "print warnings for extreme temps if fahrenheit print("it' really hot out there be careful!"if fahrenheit print("brrrrr be sure to dress warmly!"main(you can see that the python if statement is used to implement the decision the form of the if is very similar to the pseudocode in the algorithm if |
19,669 | the body is just sequence of one or more statements indented under the if heading in convert py there are two if statementsboth of which have single statement in the body the semantics of the if should be clear from the example above firstthe condition in the heading is evaluated if the condition is truethe sequence of statements in the body is executedand then control passes to the next statement in the program if the condition is falsethe statements in the body are skipped figure shows the semantics of the if as flowchart notice trueno yes figure control flow of simple if-statement that the body of the if either executes or not depending on the condition in either casecontrol then passes to the next statement after the if this is one-way or simple decision forming simple conditions one point that has not yet been discussed is exactly what condition looks like for the time beingour programs will use simple conditions that compare the values of two expressions is short for relational operator that' just fancy name for the mathematical concepts like "less thanor "equal to there are six relational operators in pythonshown in the following table |
19,670 | python <=>!mathematics <> meaning less than less than or equal to equal to greater than or equal to greater than not equal to notice especially the use of =for equality since python uses the sign to indicate an assignment statementa different symbol is required for the concept of equality common mistake in python programs is using in conditionswhere =is required conditions may compare either numbers or strings when comparing stringsthe ordering is lexicographic basicallythis means that strings are put in alphabetic order according to the underlying unicode values so all upper-case latin letters come before lower case equivalents ( "bbbbcomes before "aaaa"since "bprecedes " " should mention that conditions are actually type of expressioncalled boolean expressionafter george boolea th century english mathematician when boolean expression is evaluatedit produces value of either true (the condition holdsor false (it does not holdsome languages such as +and older versions of python just use the ints and to represent these values other languages like java and modern python have dedicated data type for boolean expressions in pythonboolean expressions are of type bool and the boolean values true and false are represented by the literals true and false here are few interactive examples true false "hello="hellotrue "hello"hellofalse "hello"hellotrue exampleconditional program execution back in mentioned that there are several different ways of running python programs some python module files are designed to be run directly these are usually referred to as "programsor "scripts other python modules are designed primarily to be imported and used by other programsthese are often called "libraries sometimes we want to create sort of hybrid module that can be used both as stand-alone program and as library that can be imported by other programs |
19,671 | decision structures so farmost of our programs have had line at the bottom to invoke the main function main(as you knowthis is what actually starts program running these programs are suitable for running directly in windowing environmentyou might run file by (double-)clicking its icon or you might type command like python py since python evaluates the lines of module during the import processour current programs also run when they are imported into either an interactive python session or into another python program generallyit is nicer not to have modules run as they are imported when testing program interactivelythe usual approach is to first import the module and then call its main (or some other functioneach time we want to run it in program designed to be either imported (without runningor run directlythe call to main at the bottom must be made conditional simple decision should do the trick if main(we just need to figure out suitable condition whenever module is importedpython sets special variable in the module called __name__ to be the name of the imported module here is an example interaction showing what happens with the math libraryimport math math __name__ 'mathyou can see thatwhen importedthe __name__ variable inside the math module is assigned the string 'mathhoweverwhen python code is being run directly (not imported)python sets the value of __name__ to be '__main__to see this in actionyou just need to start python shell and look at the value __name__ '__main__soif module is importedthe code in that module will see variable called __name__ whose value is the name of the module when file is run directlythe code will see that __name__ has the value '__main__a module can determine how it is being used by inspecting this variable putting the pieces togetherwe can change the final lines of our programs to look like thisif __name__ ='__main__'main(this guarantees that main will automatically run when the program is invoked directlybut it will not run if the module is imported you will see line of code similar to this at the bottom of virtually every python program |
19,672 | two-way decisions now that we have way to selectively execute certain statements in program using decisionsit' time to go back and spruce up the quadratic equation solver from here is the program as we left itquadratic py program that computes the real roots of quadratic equation notethis program crashes if the equation has no real roots import math def main()print("this program finds the real solutions to quadratic\ "abc eval(input("please enter the coefficients (abc)")discroot math sqrt( croot (- discroot( aroot (- discroot( aprint("\nthe solutions are:"root root main(as noted in the commentsthis program crashes when it is given coefficients of quadratic equation that has no real roots the problem with this code is that when ac is less than the program attempts to take the square root of negative number since negative numbers do not have real rootsthe math library reports an error here' an examplequadratic main(this program finds the real solutions to quadratic please enter the coefficients (abc) , , traceback (most recent call last)file "quadratic py"line in main(file "quadratic py"line in main discroot math sqrt( cvalueerrormath domain error we can use decision to check for this situation and make sure that the program can' crash here' first attempt |
19,673 | quadratic py import math def main()print("this program finds the real solutions to quadratic\ "abc eval(input("please enter the coefficients (abc)")discrim if discrim > discroot math sqrt(discrimroot (- discroot( aroot (- discroot( aprint("\nthe solutions are:"root root main(this version first computes the value of the discriminant ( acand then checks to make sure it is not negative only then does the program proceed to take the square root and calculate the solutions this program will never attempt to call math sqrt when discrim is negative unfortunatelythis updated version is not really complete solution study the program for moment what happens when the equation has no real rootsaccording to the semantics for simple ifwhen * * * is less than zerothe program will simply skip the calculations and go to the next statement since there is no next statementthe program just quits here' what happens in an interactive sessionquadratic main(this program finds the real solutions to quadratic please enter the coefficients (abc) , , this is almost worse than the previous versionbecause it does not give users any indication of what went wrongit just leaves them hanging better program would print message telling users that their particular equation has no real solutions we could accomplish this by adding another simple decision at the end of the program if discrim print("the equation has no real roots!"this will certainly solve our problembut this solution just doesn' feel right we have programmed sequence of two decisionsbut the two outcomes are mutually exclusive if discrim > is true then discrim must be false and vice versa we have two conditions in the programbut there is really only one decision to make based on the value of discrim the program |
19,674 | no discrim calculate roots yes print "no rootsfigure quadratic solver as two-way decision should either print that there are no real roots or it should calculate and display the roots this is an example of two-way decision figure illustrates the situation in pythona two-way decision can be implemented by attaching an else clause onto an if clause the result is called an if-else statement if elsewhen the python interpreter encounters this structureit will first evaluate the condition if the condition is truethe statements under the if are executed if the condition is falsethe statements under the else are executed in either casecontrol then passes to the statement following the if-else using two-way decision in the quadratic solver yields more elegant solution quadratic py import math def main()print("this program finds the real solutions to quadratic\ "abc eval(input("please enter the coefficients (abc)")discrim if discrim print("\nthe equation has no real roots!"else |
19,675 | discroot math sqrt( croot (- discroot( aroot (- discroot( aprint("\nthe solutions are:"root root main(this program fills the bill nicely here is sample session that runs the new program twicequadratic main(this program finds the real solutions to quadratic please enter the coefficients (abc) , , the equation has no real rootsquadratic main(this program finds the real solutions to quadratic please enter the coefficients (abc) , , the solutions are- - multi-way decisions the newest version of the quadratic solver is certainly big improvementbut it still has some quirks here is another example runquadratic main(this program finds the real solutions to quadratic please enter the coefficients (abc) the solutions are- - this is technically correctthe given coefficients produce an equation that has double root at - howeverthe output might be confusing to some users it looks like the program has mistakenly printed the same number twice perhaps the program should be bit more informative to avoid confusion the double-root situation occurs when discrim is exactly in this casediscroot is also and both roots have the value - if we want to catch this special caseour program actually needs three-way decision here' quick sketch of the designcheck the value of discrim when handle the case of no roots |
19,676 | when handle the case of double root when handle the case of two distinct roots one way to code this algorithm is to use two if-else statements the body of an if or else clause can contain any legal python statementsincluding other if or if-else statements putting one compound statement inside of another is called nesting here' fragment of code that uses nesting to achieve three-way decisionif discrim print("equation has no real roots"elseif discrim = root - ( aprint("there is double root at"rootelsedo stuff for two roots if you trace through this code carefullyyou will see that there are exactly three possible paths the sequencing is determined by the value of discrim flowchart of this solution is shown in figure you can see that the top-level structure is just an if-else (treat the dashed box as one big statement the dashed box contains the second if-else nested comfortably inside the else part of the top-level decision yes discrim no print "no rootsyes do double root discrim = no do unique roots figure three-way decision for quadratic solver using nested if-else once againwe have working solutionbut the implementation doesn' feel quite right we have finessed three-way decision by using two two-way decisions the resulting code does not |
19,677 | reflect the true three-fold decision of the original problem imagine if we needed to make fiveway decision using this technique the if-else structures would nest four levels deepand the python code would march off the right-hand edge of the page there is another way to write multi-way decisions in python that preserves the semantics of the nested structures but gives it more appealing look the idea is to combine an else followed immediately by an if into single clause called an elif (pronounced "ell-if"if elif elif elsethis form is used to set off any number of mutually exclusive code blocks python will evaluate each condition in turn looking for the first one that is true if true condition is foundthe statements indented under that condition are executedand control passes to the next statement after the entire if-elif-else if none of the conditions are truethe statements under the else are performed the else clause is optionalif omittedit is possible that no indented statement block will be executed using an if-elif-else to show the three-way decision in our quadratic solver yields nicely finished program quadratic py import math def main()print("this program finds the real solutions to quadratic\ "abc eval(input("please enter the coefficients (abc)")discrim if discrim print("\nthe equation has no real roots!"elif discrim = root - ( aprint("\nthere is double root at"rootelsediscroot math sqrt( croot (- discroot( aroot (- discroot( |
19,678 | print("\nthe solutions are:"root root main( exception handling our quadratic program uses decision structures to avoid taking the square root of negative number and generating an error at run-time this is common pattern in many programsusing decisions to protect against rare but possible errors in the case of the quadratic solverwe checked the data before the call to the sqrt function sometimes functions themselves check for possible errors and return special value to indicate that the operation was unsuccessful for examplea different square root operation might return negative number (say- to indicate an error since the square root function should always return the non-negative rootthis value could be used to signal that an error has occurred the program would check the result of the operation with decision discrt othersqrt( * * *cif discrt print "no real roots elsesometimes programs become so peppered with decisions to check for special cases that the main algorithm for handling the run-of-the-mill cases seems completely lost programming language designers have come up with mechanisms for exception handling that help to solve this design problem the idea of an exception handling mechanism is that the programmer can write code that catches and deals with errors that arise when the program is running rather than explicitly checking that each step in the algorithm was successfula program with exception handling can in essence say"do these stepsand if any problem crops uphandle it this way we're not going to discuss all the details of the python exception handling mechanism herebut do want to give you concrete example so you can see how exception handling works and understand programs that use it in pythonexception handling is done with special control structure that is similar to decision let' start with specific example and then take look at the general approach here is version of the quadratic program that uses python' exception mechanism to catch potential errors in the math sqrt functionquadratic py import math def main()print "this program finds the real solutions to quadratic\ntry |
19,679 | decision structures abc input("please enter the coefficients (abc)"discroot math sqrt( croot (- discroot( aroot (- discroot( aprint "\nthe solutions are:"root root except valueerrorprint "\nno real rootsmain(notice that this is basically the very first version of the quadratic program with the addition of try except around the heart of the program try statement has the general formtryexcept when python encounters try statementit attempts to execute the statements inside the body if these statements execute without errorcontrol then passes to the next statement after the try except if an error occurs somewhere in the bodypython looks for an except clause with matching error type if suitable except is foundthe handler code is executed the original program without the exception-handling produced the following errortraceback (most recent call last)file "quadratic py"line in main(file "quadratic py"line in main discroot math sqrt( cvalueerrormath domain error the last line of this error message indicates the type of error that was generatednamely an valueerror the updated version of the program provides an except clause to catch the valueerror here is the error handling version in actionthis program finds the real solutions to quadratic please enter the coefficients (abc) , , no real roots instead of crashingthe exception handler catches the error and prints message indicating that the equation does not have real roots the nice thing about the try except statement is that it can be used to catch any kind of erroreven ones that might be difficult to test forand hopefullyprovide graceful exit for examplein the quadratic solverthere are lots of other things that could go wrong besides having |
19,680 | bad set of coefficients if the user fails to type the correct number of inputsthe program generates different kind of valueerror if the user accidentally types an identifier instead of numberthe program generates nameerror if the input is not valid python expressionit generates syntaxerror if the user types in valid python expression that produces non-numeric resultsthe program generates typeerror single try statement can have multiple except clauses to catch various possible classes of errors here' one last version of the program designed to robustly handle any possible errors in the inputquadratic py import math def main()print("this program finds the real solutions to quadratic\ "tryabc eval(input("please enter the coefficients (abc)")discroot math sqrt( croot (- discroot( aroot (- discroot( aprint("\nthe solutions are:"root root except valueerror as excobjif str(excobj="math domain error"print("no real roots"elseprint("you didn' give me the right number of coefficients "except nameerrorprint("\nyou didn' enter three numbers "except typeerrorprint("\nyour inputs were not all numbers "except syntaxerrorprint("\nyour input was not in the correct form missing comma?"exceptprint("\nsomething went wrongsorry!"main(the multiple excepts are similar to elifs if an error occurspython will try each except in turn looking for one that matches the type of error the bare except at the bottom acts like an else and will be used if none of the others match if there is no default at the bottom and none of the except types match the errorthen the program crashes and python reports the error notice how handled the two different kinds of valueerrors exceptions are actually kind of object if you follow the error type with an as in an except clausepython will |
19,681 | assign that variable the actual exception object in this casei turned the exception into string and looked at the message to see what caused the valueerror notice that this text is exactly what python prints out if the error is not caught ( "valueerrormath domain error"if the exception doesn' match any of the expected typesthis program just prints general apology as challengeyou might see if you can find an erroneous input that produces the apology you can see how the try except statement allows us to write bullet-proof programs you can use this same technique by observing the error messages that python prints and designing except clauses to catch and handle them whether you need to go to this much trouble depends on the type of program you are writing in your beginning programsyou might not worry too much about bad inputhoweverprofessional quality software should do whatever is feasible to shield users from unexpected results study in designmax of three now that we have decisions that can alter the control flow of programour algorithms are liberated from the monotony of step-by-stepstrictly sequential processing this is both blessing and curse the positive side is that we can now develop more sophisticated algorithmsas we did for our quadratic solver the negative side is that designing these more sophisticated algorithms is much harder in this sectionwe'll step through the design of more difficult decision problem to illustrate some of the challenge and excitement of the design process suppose we need an algorithm to find the largest of three numbers this algorithm could be part of larger problem such as determining grades or computing taxesbut we are not interested in the final detailsjust the crux of the problem that ishow can computer determine which of three user inputs is the largesthere is program outline we need to fill in the missing part def main() eval(input("please enter three values")missing code sets max to the value of the largest print("the largest value is"maxbefore reading the following analysisyou might want to try your hand at solving this problem strategy compare each to all obviouslythis program presents us with decision problem we need sequence of statements that sets the value of max to the largest of the three inputs and at first glancethis looks like three-way decisionwe need to execute one of the following assignmentsmax max max |
19,682 | it would seem we just need to preface each one with the appropriate condition( )so that it is executed only in the proper situation let' consider the first possibilitythat is the largest to determine that is actually the largestwe just need to check that it is at least as large as the other two here is first attemptif > > max your first concern here should be whether this statement is syntactically correct the condition > > does not match the template for conditions shown above most computer languages would not accept this as valid expression it turns out that python does allow this compound conditionand it behaves exactly like the mathematical relations > > that isthe condition is true when is at least as large as and is at least as large as sofortunatelypython has no problem with this condition whenever you write decisionyou should ask yourself two crucial questions firstwhen the condition is trueare you absolutely certain that executing the body of the decision is the right action to takein this casethe condition clearly states that is at least as large as and so assigning its value to max should be correct always pay particular attention to borderline values notice that our condition includes equal as well as greater we should convince ourselves that this is correct suppose that and are all the samethis condition will return true that' ok because it doesn' matter which we choosethe first is at least as big as the othersand hencethe max the second question to ask is the converse of the first are we certain that this condition is true in all cases where is the maxunfortunatelyour condition does not meet this test suppose the values are and clearlyx is the largestbut our condition returns false since the relationship > > does not hold we need to fix this we want to ensure that is the largestbut we don' care about the relative ordering of and what we really need is two separate tests to determine that > and that > python allows us to test multiple conditions like this by combining them with the keyword and we'll discuss the exact semantics of and in intuitivelythe following condition seems to be what we are looking forif > and > max is greater than each of the others to complete the programwe just need to implement analogous tests for the other possibilities if > and > max elif > and > max elsemax |
19,683 | decision structures summing up this approachour algorithm is basically checking each possible value against all the others to determine if it is the largest with just three values the result is quite simplebut how would this solution look if we were trying to find the max of five valuesthen we would need three boolean expressionseach consisting of four conditions anded together the complex expressions result from the fact that each decision is designed to stand on its owninformation from one test is ignored in the subsequent tests to see what meanlook back at our simple max of three code suppose the first decision discovers that is greater than but not greater than at this pointwe know that must be the max unfortunatelyour code ignores thispython will go ahead and evaluate the next expressiondiscover it to be falseand finally execute the else strategy decision tree one way to avoid the redundant tests of the previous algorithm is to use decision tree approach suppose we start with simple test > this knocks either or out of contention to be the max if the condition is truewe just need to see which is largerx or should the initial condition be falsethe result boils down to choice between and as you can seethe first decision "branchesinto two possibilitieseach of which is another decisionhence the name decision tree figure shows the situation in flowchart this flowchart translates easily into nested if-else statements if > if > max elsemax elseif > max elsemax the strength of this approach is its efficiency no matter what the ordering of the three valuesthis algorithm will make exactly two comparisons and assign the correct value to max howeverthe structure of this approach is more complicated than the firstand it suffers similar complexity explosion should we try this design with more than three values as challengeyou might see if you can design decision tree to find the max of four values (you will need if-elses nested three levels deep leading to eight assignment statements strategy sequential processing so farwe have designed two very different algorithmsbut neither one seems particularly elegant perhaps there is yet third way when designing an algorithma good starting place is to ask |
19,684 | yes no > yes max > no max yes max = no max figure flowchart of the decision tree approach to max of three yourself how you would solve the problem if you were asked to do the job for finding the max of three numbersyou probably don' have very good intuition about the steps you go through you' just look at the numbers and know which is the largest but what if you were handed book containing hundreds of numbers in no particular orderhow would you find the largest in this collectionwhen confronted with the larger problemmost people develop simple strategy scan through the numbers until you find big oneand put your finger on it continue scanningif you find number bigger than the one your finger is onmove your finger to the new one when you get to the end of the listyour finger will remain on the largest value in nutshellthis strategy has us look through the list sequentiallykeeping track of the largest number seen so far computer doesn' have fingersbut we can use variable to keep track of the max so far in factthe easiest approach is just to use max to do this job that waywhen we get to the endmax automatically contains the value of the largest flowchart depicting this strategy for the max of three problem is shown in figure here is the translation into python codemax if maxmax if maxmax clearlythe sequential approach is the best of our three algorithms the code itself is quite simplecontaining only two simple decisionsand the sequencing is easier to understand than the nesting used in the previous algorithm furthermorethe idea scales well to larger problemsadding fourth item adds only one more statement max |
19,685 | max max max max max figure flowchart of sequential approach to the max of three problem if maxmax if maxmax if maxmax it should not be surprising that the last solution scales to larger problemswe invented the algorithm by explicitly considering how to solve more complex problem in factyou can see that the code is very repetitive we can easily write program that allows the user to find the largest of numbers by folding our algorithm into loop rather than having separate variables for etc we can just get the values one at time and keep reusing single variable each timewe compare the newest against the current value of max to see if it is larger programmaxn py finds the maximum of series of numbers def main() eval(input("how many numbers are there") |
19,686 | set max to be the first value max eval(input("enter number >")now compare the - successive values for in range( - ) eval(input("enter number >")if maxmax print("the largest value is"maxmain(this code uses decision nested inside of loop to get the job done on each iteration of the loopmax contains the largest value seen so far strategy use python before leaving this problemi really should mention that none of the algorithm development we have so painstakingly pursued was necessary python actually has built-in function called max that returns the largest of its parameters here is the simplest version of our programdef main() eval(input("please enter three values")print("the largest value is"max( )of coursethis version didn' require any algorithm development at allwhich rather defeats the point of the exercisesometimes python is just too simple for our own good some lessons the max of three problem is not particularly earth shatteringbut the attempt to solve this problem has illustrated some important ideas in algorithm and program design there is more than one way to do it for any non-trivial computing problemthere are many ways to approach the problem while this may seem obviousmany beginning programmers do not really take this point to heart what does this mean for youdon' rush to code up the first idea that pops into your head think about your designask yourself if there is better way to approach the problem once you have written the codeask yourself again if there might be better way your first task is to find correct algorithm after thatstrive for claritysimplicityefficiencyscalabilityand elegance good algorithms and programs are like poems of logic they are pleasure to read and maintain |
19,687 | decision structures be the computer especially for beginning programmersone of the best ways to formulate an algorithm is to simply ask yourself how you would solve the problem there are other techniques for designing good algorithms (see )howeverthe straightforward approach is often simpleclearand efficient enough generality is good we arrived at the best solution to the max of three problem by considering the more general max of numbers problem it is not unusual that consideration of more general problem can lead to better solution for some special case don' be afraid to step back and think about the overarching problem similarlywhen designing programsyou should always have an eye toward making your program more generally useful if the max of program is just as easy to write as max of threeyou may as well write the more general program because it is more likely to be useful in other situations that way you get the maximum utility from your programming effort don' reinvent the wheel our fourth solution was to use python' max function you may think that was cheatingbut this example illustrates an important point lot of very smart programmers have designed countless good algorithms and programs if the problem you are trying to solve seems to be one that lots of others must have encounteredyou might begin by finding out if the problem has already been solved for you as you are learning to programdesigning from scratch is great experience truly expert programmershoweverknow when to borrow summary this has laid out the basic control structures for making decisions here are the key points decision structures are control structures that allow program to execute different sequences of instructions for different cases decisions are implemented in python with if statements simple decisions are implemented with plain if two-way decisions generally use an if-else multi-way decisions are implemented with if-elif-else decisions are based on the evaluation of conditionswhich are simple boolean expressions boolean expression is either true or false python has dedicated bool data type with literals true and false conditions are formed using the relational operatorsand >some programming languages provide exception handling mechanisms which help to make programs more "bulletproof python provides try-except statement for exception handling algorithms that incorporate decisions can become quite complicated as decision structures are nested usually number of solutions are possibleand careful thought should be given to produce correctefficientand understandable program |
19,688 | exercises review questions true/false simple decision can be implemented with an if statement in python conditions is written as / strings are compared by lexicographic ordering two-way decision is implemented using an if-elif statement the math sqrt function cannot compute the square root of negative number single try statement can catch multiple kinds of errors multi-way decisions must be handled by nesting multiple if-else statements there is usually only one correct solution to problem involving decision structures the condition < < is allowed in python input validation means prompting user when input is required multiple choice statement that controls the execution of other statements is called aboss structure bsuper structure ccontrol structure dbranch the best structure for implementing multi-way decision in python is aif bif-else cif-elif-else dtry an expression that evaluates to either true or false is called aoperational bboolean csimple dcompound when program is being run directly (not imported),the value of __name__ is ascript bmain c__main__ dtrue the literals for type bool are atf btruefalse ctruefalse placing decision inside of another decision is an example of acloning bspooning cnesting dprocrastination |
19,689 | in pythonthe body of decision is indicated by aindentation bparentheses ccurly braces da colon structure in which one decision leads to another set of decisionswhich leads to another set of decisionsetc is called decision anetwork bweb ctree dtrap taking the square root of negative value with math sqrt produces (navalueerror bimaginary number cprogram crash dstomachache multiple choice question is most similar to asimple decision btwo-way decision cmulti-way decisions dan exception handler discussion explain the following patterns in your own words(asimple decision (btwo-way decision (cmulti-way decision the following is (sillydecision structureabc input('enter three numbers'if bif cprint "spam please!elseprint "it' late parrot!elif cprint "cheese shoppeif >cprint "cheddarelif bprint "goudaelif =bprint "swisselseprint "treesif =bprint "chestnutelse |
19,690 | print "larchprint "doneshow the output that would result from each of the following possible inputs( ( ( ( ( ( how is exception-handling using try/except similar to and different from handling exceptional cases using ordinary decision structures (variations on if)programming exercises many companies pay time-and- -half for any hours worked above in given week write program to input the number of hours worked and the hourly rate and calculate the total wages for the week certain cs professor gives -point quizzes that are graded on the scale - - - - - - write program that accepts quiz score as an input and uses decision structure to calculate the corresponding grade certain cs professor gives -point exams that are graded on the scale - : - : - : - : < : write program that accepts an exam score as input and uses decision structure to calculate the corresponding grade certain college classifies students according to credits earned student with less than credits is freshman at least credits are required to be sophomore to be junior and to be classified as senior write program that calculates class standing from the number of credits earned the body mass index (bmiis calculated as person' weight (in poundstimes divided by the square of the person' height (in inchesa bmi in the range - inclusiveis considered healthy write program that calculates person' bmi and prints message telling whether they are abovewithinor below the healthy range the speeding ticket fine policy in podunksville is $ plus $ for each mph over the limit plus penalty of $ for any speed over mph write program that accepts speed limit and clocked speed and either prints message indicating the speed was legal or prints the amount of the fineif the speed is illegal |
19,691 | babysitter charges $ an hour until : pm when the rate drops to $ an hour (the children are in bedwrite program that accepts starting time and ending time in hours and minutes and calculates the total babysitting bill you may assume that the starting and ending times are in single hour period partial hours should be appropriately prorated person is eligible to be us senator if they are at least years old and have been us citizen for at least years to be us representative these numbers are and respectively write program that accepts person' age and years of citizenship as input and outputs their eligibility for the senate and house formula for computing easter in the years - inclusiveis as followslet year% year% year% ( )% ( )% the date of easter is march (which could be in aprilwrite program that inputs yearverifies that it is in the proper rangeand then prints out the date of easter that year the formula for easter in the previous problem works for every year in the range - except for and for these years it produces date that is one week too late modify the above program to work for the entire range - year is leap year if it is divisible by unless it is century year that is not divisible by ( and are not leap years while and are write program that calculates whether year is leap year write program that accepts date in the form month/day/year and outputs whether or not the date is valid for example is validbut is not (september has only days the days of the year are often numbered from through (or this number can be computed in three steps using int arithmetic(adayn um (month day (bif the month is after february subtract ( month )/ (cif it' leap year and after february add write program that accepts date as month/day/yearverifies that it is valid date (see previous problem)and then calculates the corresponding day number do programming exercise from but add decision to handle the case where the line does not intersect the circle do programming exercise from but add decision to prevent the program from dividing by zero if the line is vertical archery scorer write program that draws an archery target (see programming exercise from and allows the user to click five times to represent arrows shot at the target using five-band scoringa bulls-eye (yellowis worth points and each successive ring is |
19,692 | worth fewer points down to for white the program should output score for each click and keep track of running sum for the entire series write program to animate circle bouncing around window the basic idea is to start the circle somewhere in the interior of the window use variables dx and dy (both initialized to to control the movement of the circle use large counted loop (say iterations)and each time through the loop move the circle using dx and dy when the -value of the center of the circle gets too high (it hits the edge)change dx to - when it gets too lowchange dx back to use similar approach for dy noteyour animation will probably run too fast you can slow it down by using the sleep function from the time library module from time import sleep sleep( pauses the program for thousandths of second take favorite programming problem from previous and add decisions and/or exception handling as required to make it truly robust (will not crash on any inputstrade your program with friend and have contest to see who can "breakthe other' program |
19,693 | decision structures |
19,694 | loop structures and booleans objectives to understand the concepts of definite and indefinite loops as they are realized in the python for and while statements to understand the programming patterns interactive loop and sentinel loop and their implementations using python while statement to understand the programming pattern end-of-file loop and ways of implementing such loops in python to be able to design and implement solutions to problems involving loop patterns including nested loop structures to understand the basic ideas of boolean algebra and be able to analyze and write boolean expressions involving boolean operators for loopsa quick review in we looked in detail at the python if statement and its use in implementing programming patterns such as one-waytwo-wayand multi-way decisions in this we'll wrap up our tour of control structures with detailed look at loops and boolean expressions you already know that the python for statement provides kind of loop it allows us to iterate through sequence of values for in the loop index variable var takes on each successive value in the sequenceand the statements in the body of the loop are executed once for each value |
19,695 | loop structures and booleans suppose we want to write program that can compute the average of series of numbers entered by the user to make the program generalit should work for any size set of numbers you know that an average is calculated by summing up the numbers and dividing by the count of how many numbers there are we don' need to keep track of all the numbers that have been enteredwe just need running sum so that we can calculate the average at the end this problem description should start some bells ringing in your head it suggests the use of some design patterns you have seen before we are dealing with series of numbers--that will be handled by some form of loop if there are numbersthe loop should execute timeswe can use the counted loop pattern we also need running sumthat calls for loop accumulator putting the two ideas togetherwe can generate design for this problem input the count of the numbersn initialize sum to loop times input numberx add to sum output average as sum hopefullyyou see both the counted loop and accumulator patterns integrated into this design we can translate this design almost directly into python implementation average py def main() eval(input("how many numbers do you have")sum for in range( ) eval(input("enter number >")sum sum print("\nthe average of the numbers is"sum nmain(the running sum starts at and each number is added in turn after the loopthe sum is divided by to compute the average here is the program in action how many numbers do you have enter number > enter number > enter number > enter number > enter number > the average of the numbers is |
19,696 | wellthat wasn' too bad knowing couple of common patternscounted loop and accumulatorgot us to working program with minimal difficulty in design and implementation hopefullyyou can see the worth of committing these sorts of programming cliches to memory indefinite loops our averaging program is certainly functionalbut it doesn' have the best user interface it begins by asking the user how many numbers there are for handful of numbers this is okbut what if have whole page of numbers to averageit might be significant burden to go through and count them up it would be much nicer if the computer could take care of counting the numbers for us unfortunatelyas you no doubt recallthe for loop (in its usual formis definite loopand that means the number of iterations is determined when the loop starts we can' use definite loop unless we know the number of iterations ahead of timeand we can' know how many iterations this loop needs until all of the numbers have been entered we seem to be stuck the solution to this dilemma lies in another kind of loopthe indefinite or conditional loop an indefinite loop keeps iterating until certain conditions are met there is no guarantee ahead of time regarding how many times the loop will go around in pythonan indefinite loop is implemented using while statement syntacticallythe while is very simple while here condition is boolean expressionjust like in if statements the body isas usuala sequence of one or more statements the semantics of while is straightforward the body of the loop executes repeatedly as long as the condition remains true when the condition is falsethe loop terminates figure shows flowchart for the while notice that the condition is always tested at the top of the loopbefore the loop body is executed this kind of structure is called pre-test loop if the loop condition is initially falsethe loop body will not execute at all here is an example of simple while loop that counts from to while < print(ii this code will have the same output as if we had written for loop like thisfor in range( )print( |
19,697 | no yes figure flowchart of while loop notice that the while version requires us to take care of initializing before the loop and incrementing at the bottom of the loop body in the for loopthe loop variable is handled automatically the simplicity of the while statement makes it both powerful and dangerous because it is less rigidit is more versatileit can do more than just iterate through sequences but it is also common source of errors suppose we forget to increment at the bottom of the loop body in the counting example while < print(iwhat will the output from this program bewhen python gets to the loopi will be which is less than so the loop body executesprinting now control returns to the conditioni is still so the loop body executes againprinting now control returns to the conditioni is still so the loop body executes againprinting you get the picture this is an example of an infinite loop usuallyinfinite loops are bad thing clearly this version of the program does nothing useful that reminds medid you hear about the computer scientist who died of exhaustion while washing his hairthe instructions on the bottle said"lather rinse repeat as beginning programmerit would be surprising if you did not accidentally write few programs with infinite loops--it' rite of passage for programmers even more experienced programmers have been known to do this from time to time usuallyyou can break out of loop by pressing - (holding down the key and pressing " "if your loop is really tightthis might not workand you'll have to resort to more drastic means (such as - |
19,698 | on pcif all else failsthere is always the trusty reset button on your computer the best idea is to avoid writing infinite loops in the first place common loop patterns interactive loops one good use of the indefinite loop is to write interactive loops the idea behind an interactive loop is that it allows the user to repeat certain portions of program on demand let' take look at this loop pattern in the context of our number averaging problem recall that the previous version of the program forced the user to count up how many numbers there were to be averaged we want to modify the program so that it keeps track of how many numbers there are we can do this with another accumulator--call it count--that starts at zero and increases by each time through the loop to allow the user to stop at any timeeach iteration of the loop will ask whether there is more data to process the general pattern for an interactive loop looks like thisset moredata to "yeswhile moredata is "yesget the next data item process the item ask user if there is moredata combining the interactive loop pattern with accumulators for the sum and count yields this algorithm for the averaging programinitialize sum to initialize count to set moredata to "yeswhile moredata is "yesinput numberx add to sum add to count ask user if there is moredata output sum count notice how the two accumulators are interleaved into the basic structure of the interactive loop here is the corresponding python programaverage py def main()sum count |
19,699 | moredata "yeswhile moredata[ =" " eval(input("enter number >")sum sum count count moredata input("do you have more numbers (yes or no)"print("\nthe average of the numbers is"sum countmain(notice this program uses string indexing (moredata[ ]to look just at the first letter of the user' input this allows for varied responses such as "yes," ,"yeah,etc all that matters is that the first letter is " here is sample output from this programenter number > do you have more numbers (yes or no)yes enter number > do you have more numbers (yes or no) enter number > do you have more numbers (yes or no) enter number > do you have more numbers (yes or no) enter number > do you have more numbers (yes or no)nope the average of the numbers is in this versionthe user doesn' have to count the data valuesbut the interface is still not good the user will almost certainly be annoyed by the constant prodding for more data the interactive loop has many good applicationsthis is not one of them sentinel loops better solution to the number averaging problem is to employ pattern commonly known as sentinel loop sentinel loop continues to process data until reaching special value that signals the end the special value is called the sentinel any value may be chosen for the sentinel the only restriction is that it be distinguishable from actual data values the sentinel is not processed as part of the data here is general pattern for designing sentinel loopsget the first data item while item is not the sentinel process the item get the next data item |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.