id
int64
0
25.6k
text
stringlengths
0
4.59k
9,600
open the python shell you see the python shell window appear change directories to the downloadable source code directory see the instructions found in the "changing the current python directorysidebar type from mylibrary import sayhello and press enter python imports the sayhello(function that you create in the "creating code groupingssectionearlier in the only this specific function is now ready for use you can still import the entire moduleshould you want to do so the two techniques for accomplishing the task are to create list of modules to import (the names can be separated by commassuch as from mylibrary import sayhellosaygoodbyeor to use the asterisk (*in place of specific attribute name the asterisk acts as wildcard character that imports everything type dir(mylibraryand press enter python displays an error messageas shown in figure - python imports only the attributes that you specifically request this means that the mylibrary module isn' in memory -only the attributes that you requested are in memory figure - the from import statement imports only the items that you specifically request type dir(sayhelloand press enter you see listing of attributes that are associated with the sayhello(functionas shown in figure - it isn' important to know how these attributes work just nowbut you'll use some of them later in the book
9,601
figure - use the dir(function to obtain information about the specific attributes you import type sayhello("angie"and press enter the sayhello(function outputs the expected textas shown in figure - figure - the say hello(function no longer requires the module name
9,602
when you import attributes using the from import statementyou don' need to precede the attribute name with module name this feature makes the attribute easier to access using the from import statement can also cause problems if two attributes have the same nameyou can import only one of them the import statement prevents name collisionswhich is important when you have large number of attributes to import in sumyou must exercise care when using the from import statement type saygoodbye("harold"and press enter you imported only the sayhello(functionso python knows nothing about saygoodbye(and displays an error message the selective nature of the from import statement can cause problems when you assume that an attribute is present when it really isn' close the python shell the python shell window closes finding modules on disk in order to use the code in modulepython must be able to locate the module and load it into memory the location information is stored as paths within python whenever you request that python import modulepython looks at all the files in its list of paths to find it the path information comes from three sourcesenvironment variables tells you about python environment variablessuch as pythonpaththat tell python where to find modules on disk current directoryearlier in this you discover that you can change the current python directory so that it can locate any modules used by your application default directorieseven when you don' define any environment variables and the current directory doesn' yield any usable modulespython can still find its own libraries in the set of default directories that are included as part of its own path information it' helpful to know the current path information because the lack of path can cause your application to fail the following steps demonstrate how you can obtain path information open the python shell you see the python shell window appear
9,603
type import sys and press enter type for in sys pathand press enter python automatically indents the next line for you the sys path attribute always contains listing of default paths type print(pand press enter twice you see listing of the path informationas shown in figure - your listing may be different from the one shown in figure - depending on your platformthe version of python you have installedand the python features you have installed figure - the sys path attribute contains listing of the individual paths for your system the sys path attribute is reliable but may not always contain every path that python can see if you don' see needed pathyou can always check in another place that python looks for information the following steps show how to perform this task type import os and press enter type os environ['pythonpath'split(os pathsepand press enter when you have pythonpath environment variable definedyou see list of pathsas shown in figure - howeverif you don' have the environment variable definedyou see an error message instead notice that both the sys path and the os environ['pythonpath'attributes contain the :\bp dentry in this case the sys path attribute doesn' include the split(function
9,604
which is why the example uses for loop with it howeverthe os environ['pythonpath'attribute does include the split(functionso you can use it to create list of individual paths you must provide split(with value to look for in splitting list of items the os pathsep constant ( variable that has oneunchangeabledefined valuedefines the path separator for the current platform so that you can use the same code on any platform that supports python close the python shell the python shell window closes figure - you must request informa tion about environment variables separately you can also add and remove items from sys path for exampleif you want to add to the list of modulesyou type sys path append(" :\bp \\"and press enter in the python shell window when you list the sys path contents againyou see that the new entry is added likewisewhen you want to remove an entrysuch as you type sys path remove(" :\\bp \\"and press enter viewing the module content python gives you several different ways to view module content the method that most developers use is to work with the dir(functionwhich tells you about the attributes that the module provides
9,605
look at figure - earlier in the in addition to the saygoodbye(and sayhello(function entries discussed previouslythe list has other entries these attributes are automatically generated by python for you these attributes perform the following tasks or contain the following information__builtins__contains listing of all the built-in attributes that are accessible from the module python adds these attributes automatically for you __cached__tells you the name and location of the cached file that is associated with the module the location information (pathis relative to the current python directory __doc__outputs help information for the moduleassuming that you've actually filled it in for exampleif you type os __doc__ and press enterpython will output the help information associated with the os library __file__tells you the name and location of the module the location information (pathis relative to the current python directory __initializing__determines whether the module is in the process of initializing itself normally this attribute returns value of false this attribute is useful when you need to wait until one module is done loading before you import another module that depends on it __loader__outputs the loader information for this module the loader is piece of software that gets the module and puts it into memory so that python can use it this is one attribute you rarely (if everuse __name__tells you just the name of the module __package__this attribute is used internally by the import system to make it easier to load and manage modules you don' need to worry about this particular attribute it may surprise you to find that you can drill down even further into the attributes type dir(mylibrary sayhelloand press enter you see the entries shown in figure - some of these entriessuch as __name__also appeared in the module listing howeveryou might be curious about some of the other entries for exampleyou might want to know what __sizeof__ is all about one way to get additional information is to type help("__sizeof__"and press enter you see some scanty (but usefulhelp informationas shown in figure -
9,606
figure - drill down as far as needed to understand the modules that you use in python figure - try getting some help information about the attribute you want to know about
9,607
python isn' going to blow up if you try the attribute even if the shell does experience problemsyou can always start new one soanother way to check out module is to simply try the attributes for exampleif you type mylibrary sayhello __sizeof__and press enteryou see the size of the sayhello(function in bytesas shown in figure - figure - using the attributes will help you get better feel for how they work unlike many other programming languagespython also makes the source code for its native language libraries available for examplewhen you look into the \python \lib directoryyou see listing of py files that you can open in idle with no problem at all try opening the os py library that you use for various tasks in this and you see the content shown in figure -
9,608
figure - directly viewing module code can help in understand ing it viewing the content directly can help you discover new programming techniques and better understand how the library works the more time you spend working with pythonthe better you'll become at using it to build interesting applications make sure that you just look at the library code and don' accidentally change it if you accidentally change the codeyour applications can stop orking worse yetyou can introduce subtle bugs into your application that will appear only on your system and nowhere else always exercise care when working with library code
9,609
using the python module documentation you can use the doc(function whenever needed to get quick help howeveryou have better way to study the modules and libraries located in the python path -the python module documentation this feature often appears as module docs in the python folder on your system it' also referred to as pydoc whatever you call itthe python module documentation makes life lot easier for developers the following sections describe how to work with this feature opening the pydoc application pydoc is just another python application it actually appears in the \python \lib directory of your system as pydoc py as with any other py fileyou can open this one with idle and study how it works you can start it using the module docs shortcut that appears in the python folder on your system or by using command at the command prompt the application creates localized server that works with your browser to display information about the python modules and libraries sowhen you start this applicationyou see command (terminalwindow open like the one shown in figure - accessing pydoc on windows the windows installation of python has prob lem when you click module docsnothing happens of coursethis is bit disconcerting because users are apt to feel that something is wrong with their systems or with python itself it turns out that the shortcut is faulty to overcome this problemyou must create new shortcut using the following steps right-click the desktop and choose new shortcut from the context menu you see the create shortcut wizard type :\python \python exe :\python lib\pydoc py - and click next this command line starts copy of the pydoc server so that you can access module information type pydoc and click finish windows creates new shortcut for you this shortcut allows you to access the module help information that currently doesn' work with python on windows
9,610
figure - starting pydoc means opening command (terminalwindow to start the server as with any serveryour system may prompt you for permissions for exampleyou may see warning from your firewall telling you that pydoc is attempting to access the local system you need to give pydoc permission to work with the system so that you can see the information it provides any virus detection that you have installed may need permission to let pydoc continue as well some platformssuch as windowsmay require an elevation in privileges to run pydoc normallythe server automatically opens new browser window for youas shown in figure - this window contains links to the various modules that are contained on your systemincluding any custom modules you create and include in the python path to see information about any moduleyou can simply click its link the command prompt provides you with two commands to control the server you simply type the letter associated with the command and press enter to activate it here are the two commandsbstarts new copy of the default browser with the index page loaded qstops the server when you're done browsing the help informationmake sure that you stop the server by typing and pressing enter at the command prompt stopping the server frees any resources it uses and closes any holes you made in your firewall to accommodate pydoc
9,611
figure - your browser displays number of links that appear as part of the index page using the quick-access links refer back to figure - near the top of the pageyou see three links these links provide quick access to the site features the browser always begins at the module index if you need to return to this pagesimply click the module index link the topics link takes you to the page shown in figure - this page contains links for essential python topics for exampleif you want to know more about boolean valuesclick the boolean link the page you see next describes how boolean values work in python at the bottom of the page are related links that lead to pages that contain additional helpful information the keywords link takes you to the page shown in figure - what you see is list of the keywords that python supports for exampleif you want to know more about creating for loopsyou click the for link
9,612
figure - the topics page tells you about essential python topicssuch as how boolean values work figure - the keywords page contains listing of keywords that python supports
9,613
typing search term the pages also include two text boxes near the top the first has get button next to it and the second has search button next to it when you type search term in the first text box and click getyou see the documentation for that particular module or attribute figure - shows what you see when you type print and click get figure - using get obtains specific information about search term when you type search term in the second text box and click searchyou see all the topics that could relate to that search term figure - shows typical results when you type print and click search in this caseyou click linksuch as calendarto see additional information
9,614
figure - using search obtains list of topics about search term viewing the results the results you get when you view page depends on the topic some topics are briefsuch as the one shown in figure - for print howeverother topics are extensive for exampleif you were to click the calendar link in figure - you would see significant amount of informationas shown in figure - in this particular caseyou see related module informationerror informationfunctionsdataand all sorts of additional information about the calendar printing functions the amount of information you see depends partly on the complexity of the topic and partly on the amount of information the developer provided with the module for exampleif you were to select mylibrary from the module index pageyou would see only list of functions and no documentation at all
9,615
figure - some pages contain extensive information
9,616
working with strings in this considering the string difference using special characters in strings working with single characters performing string-specific tasks finding what you need in string modifying the appearance of string output our computer doesn' understand strings it' basic fact computers understand numbersnot letters when you see string on the computer screenthe computer actually sees series of numbers howeverhumans understand strings quite wellso applications need to be able to work with them fortunatelypython makes working with strings relatively easy it translates the string you understand into the numbers the computer understandsand vice versa in order to make strings usefulyou need to be able to manipulate them of coursethat means taking strings apart and using just the pieces you need or searching the string for specific information this describes how you can build strings using pythondissect them as neededand use just the parts you want after you find what' required string manipulation is an important part of applications because humans depend on computers performing that sort of work for them (even though the computer has no idea of what string isafter you have the string you wantyou need to present it to the user in an eyepleasing manner the computer doesn' really care how it presents the stringso often you get the informationbut it lacks pizzazz in factit may be downright difficult to read knowing how to format strings so that they look nice onscreen is important because users need to see information in form they understand by the time you complete this you know how to createmanipulateand format strings so that the user sees precisely the right information
9,617
understanding that strings are different most aspiring developers (and even few who have written code for long timereally have hard time understanding that computers truly do only understand and even larger numbers are made up of and comparisons take place with and data is moved using and in shortstrings don' exist for the computer (and numbers just barely existalthough grouping and to make numbers is relatively easystrings are lot harder because now you're talking about information that the computer must manipulate as numbers but present as characters there are no strings in computer science strings are made up of charactersand individual characters are actually numeric values when you work with strings in pythonwhat you're really doing is creating an assembly of characters that the computer sees as numeric values that' why the following sections are so important they help you understand why strings are so special understanding this material will save you lot of headaches later defining character using numbers to create characteryou must first define relationship between that character and number more importanteveryone must agree that when certain number appears in an application and is viewed as character by that applicationthe number is translated into specific character one of the most common ways to perform this task is to use the american standard code for information interchange (asciipython uses ascii to translate the number to the letter the chart at shows the various numeric values and their character equivalents every character you use must have different numeric value assigned to it the letter uses value of to create lowercase ayou must assign different numberwhich is the computer views and as completely different characterseven though people view them as uppercase and lowercase versions of the same character the numeric values used in this are in decimal howeverthe computer still views them as and for examplethe letter is really the value and the letter is really the value when you see an onscreenthe computer sees binary value instead
9,618
having just one character set to deal with would be nice howevernot everyone could agree on single set of numeric values to equate with specific characters part of the problem is that ascii doesn' support characters used by other languagesalsoit lacks the capability to translate special characters into an onscreen presentation in factcharacter sets abound you can see number of them at html click one of the character set entries to see how it assigns specific numeric values to each character most characters sets do use ascii as starting point using characters to create strings python doesn' make you jump through hoops to create strings howeverthe term string should actually give you good idea of what happens think about beads or anything else you might string you place one bead at time onto the string eventually you end up with some type of ornamentation -perhaps necklace or tree garland the point is that these items are made up of individual beads the same concept used for necklaces made of beads holds true for strings in computers when you see sentenceyou understand that the sentence is made up of individual characters that are strung together by the programming language you use the language creates structure that holds the individual characters together sothe languagenot the computerknows that so many numbers in row (each number being represented as characterdefines string such as sentence you may wonder why it' important to even know how python works with characters the reason is that many of the functions and special features that python provides work with individual charactersand it' important to know that python sees the individual characters even though you see sentencepython sees specific number of characters unlike most programming languagesstrings can use either single quotes or double quotes for example"hello there!with double quotes is stringas is 'hello there!with single quotes python also supports triple double and single quotes that let you create strings spanning multiple lines the following steps help you create an example that demonstrates some of the string features that python provides this example also appears with the downloadable source code as basicstring py open python file window you see an editor in which you can type the example code
9,619
type the following code into the window -pressing enter after each lineprint('hello there (single quote)!'print("hello there (double quote)!"print("""this is multiple line string using triple double quotes you can also use triple single quotes """each of the three print(function calls demonstrates different principle in working with strings it' equally acceptable to enclose the string in either single or double quotes when you use triple quote (either single or double)the text can appear on multiple lines choose runrun module you see python shell window open the application outputs the text notice that the multiline text appears on three lines (see figure - )just as it does in the source code fileso this is kind of formatting you can use multiline formatting to ensure that the text breaks where you want it to onscreen figure - strings consist of individual characters that are linked together creating stings with special characters some strings include special characters these characters are different from the alphanumeric and punctuation characters that you're used to using in factthey fall into these categoriescontrolan application requires some means of determining that particular character isn' meant to be displayed but rather to control the display all the control movements are based on the insertion pointerthe
9,620
line you see when you type text on the screen for exampleyou don' see tab character the tab character provides space between two elementsand the size of that space is controlled by tab stop likewisewhen you want to go to the next lineyou use carriage return (which returns the insertion pointer to the beginning of the lineand linefeed (which places the insertion pointer on the next linecombination accentedcharacters that have accentssuch as the acute (')grave (`)circumflex (^)umlaut or diaeresis (")tilde (~)or ring represent special spoken soundsin most cases you must use special characters to create alphabetical characters with these accents included drawingit' possible to create rudimentary art with some characters you can see examples of the box-drawing characters at net/ /unicode/ - some people actually create art using ascii characters as well typographicala number of typographical characterssuch as the pilcrow ( ),are used when displaying certain kinds of text onscreenespecially when the application acts as an editor otherdepending on the character set you usethe selection of characters is nearly endless you can find character for just about any need the point is that you need some means of telling python how to present these special characters common need when working with stringseven strings from simple console applicationsis control characters with this in mindpython provides escape sequences that you use to define control characters directly (and special escape sequence for other charactersan escape sequence literally escapes the common meaning of lettersuch as aand gives it new meaning (such as the ascii bell or beepthe combination of the backslash (\and letter (such as ais commonly viewed as single letter by developers -an escape character or escape code table - provides an overview of these escape sequences table - python escape sequences escape sequence meaning \newline ignored \backslash (\\single quote ('\double quote ("(continued
9,621
table - (continuedescape sequence meaning \ ascii bell (bel\ ascii backspace (bs\ ascii formfeed (ff\ ascii linefeed (lf\ ascii carriage return (cr\ ascii horizontal tab (tab\uhhhh unicode character ( specific kind of character set with broad appeal across the worldwith hexadecimal value that replaces hhhh \ ascii vertical tab (vt\ooo ascii character with octal numeric value that replaces ooo \xhh ascii character with hexadecimal value that replaces hh the best way to see how the escape sequences work is to try them the following steps help you create an example that tests various escape sequences so that you can see them in action this example also appears with the downloadable source code as specialcharacters py open python file window you see an editor in which you can type the example code type the following code into the window -pressing enter after each lineprint("part of this text\ \nis on the next line "print("this is an with grave accent\xc "print("this is drawing character\ "print("this is pilcrow\ "print("this is division sign\xf "the example code uses various techniques to achieve the same end -to create special character of courseyou use control characters directlyas shown in the first line many special letters are accessible using hexadecimal number that has two digits (as in the second and fifth lineshoweversome require that you rely on unicode numbers (which always require four digits)as shown in the third line octal values use three digits and have no special character associated with themas shown in the fourth line
9,622
choose runrun module you see python shell window open the application outputs the expected text and special charactersas shown in figure - the python shell uses standard character set across platformsso the python shell should use the same special characters no matter which platform you test howeverwhen creating your applicationmake sure to test it on various platforms to see how the application will react character set on one platform may use different numbers for special characters than another platform does in additionuser selection of character sets could have an impact on how special characters displayed by your application appear always make sure that you test special character usage completely figure - use special characters as needed to present special information or to format the output selecting individual characters earlier in the you discover that strings are made up of individual characters they arein factjust like beads on necklace -with each bead being an individual element of the whole string python makes it possible to access individual characters in string this is an important feature because you can use it to create new strings that contain only part of the original in additionyou can combine strings to create new results the secret to this feature is the square bracket you place square bracket with number in it after the name of the variable here' an examplemystring "hello worldprint(mystring[ ]
9,623
in this casethe output of the code is the letter python strings are zerobasedwhich means they start with the number and proceed from there for exampleif you were to type print(mystring[ ])the output would be the letter you can also obtain range of characters from string simply provide the beginning and ending letter count separated by colon in the square brackets for exampleprint(mystring[ : ]would output the word world the output would begin with letter and end with letter (remember that the index is zero basedthe following steps demonstrate some basic tasks that you can perform using python' character-selection technique this example also appears with the downloadable source code as characters py open python file window you see an editor in which you can type the example code type the following code into the window -pressing enter after each line string "hello worldstring "python is fun!print(string [ ]print(string [ : ]print(string [: ]print(string [ :]string string [: string [: print(string print(string [: ]* the example begins by creating two strings it then demonstrates various methods for using the index on the first string notice that you can leave out the beginning or ending number in range if you want to work with the remainder of that string the next step is to combine two substrings in this casethe code combines the beginning of string with the beginning of string to create string the use of the sign to combine two strings is called concatenation it' one of the handier operators to remember when you're working with strings in an application the final step is to use python feature called repetition you use repetition to make number of copies of string or substring
9,624
choose runrun module you see python shell window open the applications outputs series of substrings and string combinationsas shown in figure - figure - you can select individual pieces of string slicing and dicing strings working with ranges of characters provides some degree of flexibilitybut it doesn' provide you with the capability to actually manipulate the string content or discover anything about it for exampleyou might want to change the characters to uppercase or determine whether the string contains all letters fortunatelypython has functions that help you perform tasks of this sort here are the most commonly used functionscapitalize()capitalizes the first letter of string center(widthfillchar=")centers string so that it fits within the number of spaces specified by width if you supply character for fillcharthe function uses that character otherwisecenter(uses spaces to create string of the desired width expandtabs(tabsize= )expands tabs in string by replacing the tab with the number of spaces specified by tabsize the function defaults to spaces per tab when tabsize isn' provided isalnum()returns true when the string has at least one character and all characters are alphanumeric (letters or numbersisalpha()returns true when the string has at least one character and all characters are alphabetic (letters onlyisdecimal()returns true when unicode string contains only decimal characters
9,625
isdigit()returns true when string contains only digits (numbers and not lettersislower()returns true when string has at least one alphabetic character and all alphabetic characters are in lowercase isnumeric()returns true when unicode string contains only numeric characters isspace()returns true when string contains only whitespace characters (which includes spacestabscarriage returnslinefeedsform feedsand vertical tabsbut not the backspaceistitle()returns true when string is cased for use as titlesuch as hello world howeverthe function requires that even little words have the title case for examplefollow star returns falseeven though it' properly casedbut follow star returns true isupper()returns true when string has at least one alphabetic character and all alphabetic characters are in uppercase join(seq)creates string in which the base string is separated in turn by each character in seq in repetitive fashion for exampleif you start with mystring "helloand type print(mystring join("!*!"))the output is !hello*hellolen(string)obtains the length of string ljust(widthfillchar=")left justifies string so that it fits within the number of spaces specified by width if you supply character for fillcharthe function uses that character otherwiseljust(uses spaces to create string of the desired width lower()converts all uppercase letters in string to lowercase letters lstrip()removes all leading whitespace characters in string max(str)returns the character that has the maximum numeric value in str for examplea would have larger numeric value than min(str)returns the character that has the minimum numeric value in str for examplea would have smaller numeric value than rjust(widthfillchar=")right justifies string so that it fits within the number of spaces specified by width if you supply character for fillcharthe function uses that character otherwiserjust(uses spaces to create string of the desired width rstrip()removes all trailing whitespace characters in string split(str="num=string count(str))splits string into substrings using the delimiter specified by str (when suppliedthe default is to use space as delimiter consequentlyif your string contains fine daythe output would be three substrings consisting of afineand day you use num to define the number of substrings to return the default is to return every substring that the function can produce
9,626
splitlines(num=string count('\ '))splits string that contains newline (\ncharacters into individual strings each break occurs at the newline character the output has the newline characters removed you can use num to specify the number of strings to return strip()removes all leading and trailing whitespace characters in string swapcase()inverts the case for each alphabetic character in string title()returns string in which the initial letter in each word is in uppercase and all remaining letters in the word are in lowercase upper()converts all lowercase letters in string to uppercase letters zfill (width)returns string that is left-padded with zeros so that the resulting string is the size of width this function is designed for use with strings containing numeric values it retains the original sign information (if anysupplied with the number playing with these functions bit can help you understand them better the following steps create an example that demonstrates some of the tasks you can perform using these functions this example also appears with the downloadable source code as functions py open python file window you see an editor in which you can type the example code type the following code into the window -pressing enter after each linemystring hello world print(mystring upper()print(mystring strip()print(mystring center( "*")print(mystring strip(center( "*")print(mystring isdigit()print(mystring istitle()print(max(mystring)print(mystring split()print(mystring split()[ ]the code begins by creating mystringwhich includes spaces before and after the text so that you can see how space-related functions work the initial task is to convert all the characters to uppercase
9,627
removing extra space is common task in application development the strip(function performs this task well the center(function lets you add padding to both the left and right side of string so that it consumes desired amount of space when you combine the strip(and center(functionsthe output is different from when you use the center(function alone you can combine functions to produce desired result python executes each of the functions one at time from left to right the order in which the functions appear will affect the outputand developers commonly make the mistake of putting the functions in the wrong order if your output is different from what you expectedtry changing the function order some functions work on the string as an input rather than on the string instance the max(function falls into this category if you had typed mystring max()python would have displayed an error the bulleted list that appears earlier in this section shows which functions require this sort of string input when working with functions that produce list as an outputyou can access an individual member by providing an index to it the example shows how to use split(to split the string into substrings it then shows how to access just the first substring in the list you find out more about working with lists in choose runrun module you see python shell window open the application outputs number of modified stringsas shown in figure - figure - using functions makes string manipu lation lot more flexible
9,628
locating value in string there are times when you need to locate specific information in string for exampleyou may want to know whether string contains the word hello in it one of the essential purposes behind creating and maintaining data is to be able to search it later to locate specific bits of information strings are no different -they're most useful when you can find what you need quickly and without any problems python provides number of functions for searching strings here are the most commonly used functionscount(strbeg end=len(string))counts how many times str occurs in string you can limit the search by specifying beginning index using beg or an ending index using end endswith(suffixbeg= end=len(string))returns true when string ends with the characters specified by suffix you can limit the check by specifying beginning index using beg or an ending index using end find(strbeg= end=len(string))determines whether str occurs in string and outputs the index of the location you can limit the search by specifying beginning index using beg or ending index using end index(strbeg= end=len(string))provides the same functionality as find()but raises an exception when str isn' found replace(oldnew [max])replaces all occurrences of the character sequence specified by old in string with the character sequence specified by new you can limit the number of replacements by specifying value for max rfind(strbeg= end=len(string))provides the same functionality as find()but searches backward from the end of the string instead of the beginning rindex(strbeg= end=len(string))provides the same functionality as index()but searches backward from the end of the string instead of the beginning startswith(prefixbeg= end=len(string))returns true when string begins with the characters specified by prefix you can limit the check by specifying beginning index using beg or an ending index using end finding the data that you need is an essential programming task -one that is required no matter what kind of application you create the following steps help you create an example that demonstrates the use of search functionality within strings this example also appears with the downloadable source code as searchstring py
9,629
open python file window you see an editor in which you can type the example code type the following code into the window -pressing enter after each linesearchme "the apple is red and the berry is blue!print(searchme find("is")print(searchme rfind("is")print(searchme count("is")print(searchme startswith("the")print(searchme endswith("the")print(searchme replace("apple""car"replace("berry""truck")the example begins by creating searchmea string with two instances of the word is the two instances are important because they demonstrate how searches differ depending on where you start when using find()the example starts from the beginning of the string by contrastrfind(starts from the end of the string of courseyou won' always know how many times certain set of characters appears in string the count(function lets you determine this value depending on the kind of data you work withsometimes the data is heavily formatted and you can use particular pattern to your advantage for exampleyou can determine whether particular string (or substringends or begins with specific sequence of characters you could just as easily use this technique to look for part number the final bit of code replaces apple with car and berry with truck notice the technique used to place the code on two lines in some casesyour code will need to appear on multiple lines to make it more readable choose runrun module you see python shell window open the application displays the output shown in figure - notice especially that the searches returned different indexes based on where they started in the string using the correct function when performing searches is essential to ensure that you get the results you expected
9,630
figure - typing the wrong input type generates an error instead of an exception formatting strings you can format strings in number of ways using python the main emphasis of formatting is to present the string in form that is both pleasing to the user and easy to understand formatting doesn' mean adding special fonts or effects in this casebut refers merely to the presentation of the data for examplethe user might want fixed-point number rather than decimal number as output you have quite few ways to format strings and you see number of them as the book progresses howeverthe focus of most formatting is the format(function you create formatting specification as part of the string and then use the format(function to add data to that string format specification may be as simple as two curly brackets {that specify placeholder for data you can number the placeholder to create special effects for example{ would contain the first data element in string when the data elements are numberedyou can even repeat them so that the same data appears more than once in the string the formatting specification follows colon when you want to create just formatting specificationthe curly brackets contain just the colon and whatever formatting you want to use for example{:fwould create fixed-point number as output if you want to number the entriesthe number that precedes the colon{ :fcreates fixed-point number output for data element one the formatting specification follows this formwith the italicized elements serving as placeholders here[[fill]align][sign][#][ ][width][,]precision][type
9,631
the specification at html provides you with the in-depth detailsbut here' an overview of what the various entries meanfilldefines the fill character used when displaying data that is too small to fit within the assigned space alignspecifies the alignment of data within the display space you can use these alignments<left aligned >right aligned ^centered =justified signdetermines the use of signs for the output+positive numbers have plus sign and negative numbers have minus sign -negative numbers have minus sign positive numbers are preceded by space and negative numbers have minus sign #specifies that the output should use the alternative display format for numbers for examplehexadecimal numbers will have prefix added to them specifies that the output should be sign aware and padded with zeros as needed to provide consistent output widthdetermines the full width of the data field (even if the data won' fit in the space provided,specifies that numeric data should have commas as thousands separator precisiondetermines the number of characters after the decimal point typespecifies the output typeeven if the input type doesn' match the types are split into three groupsstringuse an or nothing at all to specify string integerthe integer types are as followsb (binary) (character) (decimal) (octal) (hexadecimal with lowercase letters) (hexadecimal with uppercase letters)and (locale-sensitive decimal that uses the appropriate characters for the thousands separator
9,632
floating pointthe floating-point types are as followse (exponent using lowercase as separator) (exponent using an uppercase as separator) (lowercase fixed point) (uppercase fixed point) (lowercase general format) (uppercase general format) (local-sensitive general format that uses the appropriate characters for the decimal and thousands separators)and (percentagethe formatting specification elements must appear in the correct order or python won' know what to do with them if you specify the alignment before the fill characterpython displays an error message rather than performing the required formatting the following steps help you see how the formatting specification works and demonstrate the order you need to follow in using the various formatting specification criteria this example also appears with the downloadable source code as formatted py open python file window you see an editor in which you can type the example code type the following code into the window -pressing enter after each lineformatted "{: }print(formatted format( )formatted "{:, }print(formatted format( )formatted "{:^ , }print(formatted format( )formatted "{:*^ , }print(formatted format( )formatted "{:*^ }print(formatted format( )formatted "{:*> }print(formatted format( )formatted "{:*<# }print(formatted format( )formatted " { { and { { print(formatted format("blue""car""truck")
9,633
the example starts simply with field formatted as decimal value it then adds thousands separator to the output the next step is to make the field wider than needed to hold the data and to center the data within the field finallythe field has an asterisk added to pad the output of coursethere are other data types in the example the next step is to display the same data in fixed-point format the example also shows the output in both uppercase and lowercase hexadecimal format the uppercase output is right aligned and the lowercase output is left aligned finallythe example shows how you can use numbered fields to your advantage in this caseit creates an interesting string output that repeats one of the input values choose runrun module you see python shell window open the application outputs data in various formsas shown in figure - figure - use formatting to present data in precisely the form you want
9,634
managing lists in this defining why lists are important generating lists looking through lists working with list items sequentially changing list content locating specific information in lists putting list items in order using the counter object to your advantage lot of people lose sight of the fact that most programming techniques are based on the real world part of the reason is that programmers often use terms that other people don' to describe these real-world objects for examplemost people would call place to store something box or cupboard -but programmers insist on using the term variable lists are different everyone makes lists and uses them in various ways to perform an abundance of tasks in factyou're probably surrounded by lists of various sorts where you're sitting right now as you read this book sothis is about something you already use quite lot the only difference is that you need to think of lists in the same way python does you may read that lists are hard to work with the reason that some people find working with lists difficult is that they're not used to actually thinking about the lists they create when you create listyou simply write items down in whatever order makes sense to you sometimes you rewrite the list when you're done to put it in specific order in other casesyou use your finger as guide when going down the list to make looking through it easier the point is that everything you normally do with lists is also doable within python the difference is that you must now actually think about what you're doing in order to make python understand what you want done
9,635
lists are incredibly important in python this introduces you to the concepts used to createmanagesearchand print lists (among other taskswhen you complete the you can use lists to make your python applications more robustfasterand more flexible in factyou'll wonder how you ever got along without using lists in the past the important thing to keep in mind is that you have already used lists most of your life there really isn' any difference now except that you must now think about the actions that you normally take for granted when managing your own lists organizing information in an application people create lists to organize information and make it easier to access and change you use lists in python for the same reason in many situationsyou really do need some sort of organizational aid to hold data for exampleyou might want to create single place to look for days of the week or months of the year the names of these items would appear in listmuch as they would if you needed to commit them to paper in the real world the following sections describe lists and how they work in more detail defining organization using lists the python specification defines list as kind of sequence sequences simply provide some means of allowing multiple data items to exist together in single storage unitbut as separate entities think about one of those large mail holders you see in apartment buildings single mail holder contains number of small mailboxeseach of which can contain mail python supports other kinds of sequences as well discusses number of these sequences)tuples dictionaries stacks queues deques of all the sequenceslists are the easiest to understand and are the most directly related to real-world object working with lists helps you become better able to work with other kinds of sequences that provide greater functionality and improved flexibility the point is that the data is stored in list much as you would write it on piece of paper -one item comes after
9,636
anotheras shown in figure - the list has beginninga middleand an end as shown in the figurethe items are numbered (even if you might not normally number them in real lifepython always numbers the items for you figure - list is simply sequence of itemsmuch as you would write on notepad understanding how computers view lists the computer doesn' view lists in the same way that you do it doesn' have an internal notepad and use pen to write on it computer has memory the computer stores each item in list in separate memory locationas shown in figure - the memory is contiguousso as you add new itemsthey're added to the next location in memory figure - each item added to list takes the next position in memory in many respectsthe computer uses something like mailbox to hold your list the list as whole is the mail holder as you add itemsthe computer places it in the next mailbox within the mail holder
9,637
just as the mailboxes are numbered in mail holderthe memory slots used for list are numbered the numbers begin with not with as you might expect each mailbox receives the next number in line mail holder with the months of the year would contain mailboxes the mailboxes would be numbered from to (not as you might thinkit' essential to get the numbering scheme down as quickly as possible because even experienced developers get into trouble by using and not as starting point at times depending on what sort of information you place in each mailboxthe mailboxes need not be of the same size python lets you store string in one mailboxan integer in anotherand floating-point value in another the computer doesn' know what kind of information is stored in each mailbox and it doesn' care all the computer sees is one long list of numbers that could be anything python performs all the work required to treat the data elements according to the right type and to ensure that when you request item fiveyou actually get item five in generalit' good practice to create lists of like items to make the data easier to manage when creating list of all integersfor examplerather than of mixed datayou can make assumptions about the information and don' have to spend nearly as much time checking it howeverin some situationsyou might need to mix data many other programming languages require that lists have just one type of databut python offers the flexibility of using mixed data sorts just remember that using mixed data in list means that you must determine the data type when retrieving the information in order to work with the data correctly treating string as an integer would cause problems in your application creating lists as in real lifebefore you can do anything with listyou must create it as previously statedpython lists can mix types howeverit' always best practice to restrict list to single type when you can the following steps demonstrate how to create python lists open python shell window you see the familiar python prompt type list ["one" "two"trueand press enter python creates list named list for you this list contains two string values (one and two)an integer value ( )and boolean value (trueof courseyou can' actually see anything because python processes the command without saying anything
9,638
notice that each data type that you type is different color when you use the default color schemepython displays strings in greennumbers in blackand boolean values in orange the color of an entry is cue that tells you whether you have typed the entry correctlywhich helps reduce errors when creating list type print(list and press enter you see the content of the list as wholeas shown in figure - notice that the string entries appear in single quoteseven though you typed them using double quotes strings can appear in either single quotes or double quotes in python figure - python displays the content of list type dir(list and press enter python displays list of actions that you can perform using listsas shown in figure - notice that the output is actually list soyou're using list to determine what you can do with another list figure - python provides listing of the actions you can perform using list
9,639
as you start working with objects of greater complexityyou need to remember that the dir(command always shows what tasks you can perform using that object the actions that appear without underscores are the main actions that you can perform using list these actions are the followingappend clear copy count extend index insert pop remove reverse sort close the python shell window accessing lists after you create listyou want to access the information it contains an object isn' particularly useful if you can' at least access the information it contains the previous section shows how to use the print(and dir(functions to interact with listbut there are other ways to perform the taskas described in the following steps open python shell window you see the familiar python prompt type list ["one" "two"trueand press enter python creates list named list for you
9,640
type list [ and press enter you see the value as outputas shown in figure - the use of number within set of square brackets is called an index python always uses zero-based indexesso asking for the element at index means getting the second element in the list figure - make sure to use the cor rect index number type list [ : and press enter you see range of values that includes two elementsas shown in figure - when typing rangethe end of the range is always one greater than the number of elements returned in this casethat means that you get elements and not elements through as you might expect figure - ranges return mul tiple values type list [ :and press enter you see all the elementsstarting from element to the end of the listas shown in figure - range can have blank ending numberwhich simply means to print the rest of the list
9,641
figure - leaving the ending number of range blank prints the rest of the list type list [: and press enter python displays the elements from through leaving the start of range blank means that you want to start with element as shown in figure - figure - leaving the beginning number of range blank prints from element close the python shell window even though it' really confusing to do soyou can use negative indexes with python instead of working from the leftpython will work from the right and backward for exampleif you have list ["one" "two"trueand type list [- ]you get two as output likewisetyping list[- results in an output of the rightmost element is element - in this case
9,642
looping through lists to automate the processing of list elementsyou need some way to loop through the list the easiest way to perform this task is to rely on for statementas described in the following steps this example also appears with the downloadable source code as listloop py open python file window you see an editor in which you can type the example code type the following code into the window -pressing enter after each linelist [ for item in list print(itemthe example begins by creating list consisting of numeric values it then uses for loop to obtain each element in turn and print it onscreen choose runrun module you see python shell window open the output shows the individual values in the listone on each lineas shown in figure - figure - loop makes it easy to obtain copy of each item and process it as needed
9,643
modifying lists you can modify the content of list as needed modifying list means to change particular entryadd new entryor remove an existing entry to perform these tasksyou must sometimes read an entry the concept of modification is found within the acronym crudwhich stands for createreadupdateand delete here are the list functions associated with crudappend()adds new entry to the end of the list clear()removes all entries from the list copy()creates copy of the current list and places it in new list extend()adds items from an existing list and into the current list insert()adds new entry to the position specified in the list pop()removes an entry from the end of the list remove()removes an entry from the specified position in the list the following steps show how to perform modification tasks with lists this is hands-on exercise as the book progressesyou see these same functions used within application code the purpose of this exercise is to help you gain feel for how lists work open python shell window you see the familiar python prompt type list [and press enter python creates list named list for you notice that the square brackets are empty list doesn' contain any entries you can create empty lists that you fill with information later in factthis is precisely how many lists start because you usually don' know what information they will contain until the user interacts with the list type len(list and press enter the len(function outputs as shown in figure - when creating an applicationyou can check for an empty list using the len(function if list is emptyyou can' perform tasks such as removing elements from it because there is nothing to remove type list append( and press enter
9,644
figure - check for empty lists as needed in your application type len(list and press enter the len(function now reports length of type list [ and press enter you see the value stored in element of list as shown in figure - figure - appending an element changes the list length and stores the value at the end of the list type list insert( and press enter the insert(function requires two arguments the first argument is the index of the insertionwhich is element in this case the second argument is the object you want inserted at that pointwhich is in this case type list and press enter python has added another element to list howeverusing the insert(function lets you add the new element before the first elementas shown in figure -
9,645
figure - inserting provides flexibility in decid ing where to add an element type list list copyand press enter the new listlist is precise copy of list copying is often used to create temporary version of an existing list so that user can make temporary modifications to it rather than to the original list when the user is donethe application can either delete the temporary list or copy it to the original list type list extend(list and press enter python copies all the elements in list to the end of list extending is commonly used to consolidate two lists type list and press enter you see that the copy and extend processes have worked list now contains the values and as shown in figure - type list pop(and press enter python displays value of as shown in figure - the was stored at the end of the listand pop(always removes values from the end type list remove( and press enter this timepython removes the item at element unlike the pop(functionthe remove(function doesn' display the value of the item it removed type list clear(and press enter using clear(means that the list shouldn' contain any elements now
9,646
figure - copying and extending provide methods for moving lot of data around quickly figure - use pop(to remove elements from the end of list
9,647
using operators with lists lists can also rely on operators to perform cer tain tasks for exampleif you want to create list that contains four copies of the word helloyou could use mylist ["hello" to fill it list allows repetition as needed the multiplication operator (*tells python how many times to repeat given item it' essen tial to remember that every repeated ele ment is separateso what mylist contains is ['hello''hello''hello''hello'you can also use concatenation to fill list for exampleusing mylist ["hello"["world"["!" creates six elements in mylist the first element is hellofollowed by world and ending with four ele ments with one exclamation mark (!in each element the membership operator (inalso works with lists this uses straightforward and easy-to-understand method of searching lists (the recommended approachhoweveryou can use the membership operator to make things shorter and simpler by using "helloin mylist assuming that you have your list filled with ['hello''world''!''!''!''!']the output of this state ment is true type len(list and press enter you see that the output is list is definitely empty at this pointyou've tried all the modification methods that python provides for lists work with list some more using these various functions until you feel comfortable making changes to the list close the python shell window searching lists modifying list isn' very easy when you don' know what the list contains the ability to search list is essential if you want to make maintenance tasks easier the following steps help you create an application that demonstrates the ability to search list for specific values this example also appears with the downloadable source code as searchlist py open python file window you see an editor in which you can type the example code type the following code into the window -pressing enter after each line
9,648
colors ["red""orange""yellow""green""blue"colorselect "while str upper(colorselect!"quit"colorselect input("please type color name"if (colors count(colorselect> )print("the color exists in the list!"elif (str upper(colorselect!"quit")print("the list doesn' contain the color "the example begins by creating list named colors that contains color names it also creates variable named colorselect to hold the name of the color that the user wants to find the application then enters loop where the user is asked for color name that is placed in colorselect as long as this variable doesn' contain the word quitthe application continues loop that requests input whenever the user inputs color namethe application asks the list to count the number of occurrences of that color when the value is equal to or greater than onethe list does contain the color and an appropriate message appears onscreen on the other handwhen the list doesn' contain the requested coloran alternative message appears onscreen notice how this example uses an elif clause to check whether colorselect contains the word quit this technique of including an elif clause ensures that the application doesn' output message when the user wants to quit the application you need to use similar techniques when you create your applications to avoid potential user confusion or even data loss (when the application performs task the user didn' actually request choose runrun module you see python shell window open the application asks you to type color name type blue and press enter you see message telling you that the color does exist in the listas shown in figure - type purple and press enter you see message telling you that the color doesn' existas shown in figure - type quit and press enter the application ends notice that the application displays neither success nor failure message
9,649
figure - colors that exist in the list receive the success message figure - entering color that doesn' exist results in failure message sorting lists the computer can locate information in list no matter what order it appears in it' factthoughthat longer lists are easier to search when you put them in sorted order howeverthe main reason to put list in sorted order is to make it easier for the human user to actually see the information the list contains people work better with sorted information this example begins with an unsorted list it then sorts the list and outputs it to the display the following steps demonstrate how to perform this task this example also appears with the downloadable source code as sortlist py
9,650
open python file window you see an editor in which you can type the example code type the following code into the window -pressing enter after each linecolors ["red""orange""yellow""green""blue"for item in colorsprint(itemend="print(colors sort(for item in colorsprint(itemend="print(the example begins by creating an array of colors the colors are currently in unsorted order the example then prints the colors in the order in which they appear notice the use of the end=argument for the print(function to ensure that all color entries remain on one line (making them easier to comparesorting the list is as easy as calling the sort(function after the example calls the sort(functionit prints the list again so that you can see the result choose runrun module you see python shell window open the application outputs both the unsorted and sorted listsas shown in figure - figure - sorting list is as easy as calling the sort(function
9,651
you may need to sort items in reverse order at times to accomplish this taskyou use the reverse(function the function must appear on separate line so the previous example would look like this if you wanted to sort the colors in reverse ordercolors ["red""orange""yellow""green""blue"for item in colorsprint(itemend="print(colors sort(colors reverse(for item in colorsprint(itemend="print(working with the counter object sometimes you have data source and you simply need to know how often things happen (such as the appearance of certain item in the listwhen you have short listyou can simply count the items howeverwhen you have really long listit' nearly impossible to get an accurate count for exampleconsider what it would take if you had really long novel like war and peace in list and wanted to know the frequency of the words the novel used the task would be impossible without computer the counter object lets you count items quickly in additionit' incredibly easy to use this book shows the counter object in use number of timesbut this shows how to use it specifically with lists the example in this section creates list with repetitive elements and then counts how many times those elements actually appear this example also appears with the downloadable source code as usecounterwithlist py open python file window you see an editor in which you can type the example code type the following code into the window -pressing enter after each line
9,652
from collections import counter mylist [ listcount counter(mylistprint(listcountfor thisitem in listcount items()print("item"thisitem[ ]appears"thisitem[ ]print("the value appears { times format(listcount get( ))in order to use the counter objectyou must import it from collections of courseif you work with other collection types in your applicationyou can import the entire collections module by typing import collections instead the example begins by creating listmylistwith repetitive numeric elements you can easily see that some elements appear more than once the example places the list into new counter objectlistcount you can create counter objects in all sorts of waysbut this is the most convenient method when working with list the counter object and the list aren' actually connected in any way when the list content changesyou must re-create the counter object because it won' automatically see the change an alternative to re-creating the counter is to call the clear(method first and then call the update(method to fill the counter object with the new data the application prints listcount in various ways the first output is the counter as it appears without any manipulation the second output prints the individual unique elements in mylist along with the number of times each element appears to obtain both the element and the number of times it appearsyou must use the items(function as shown finallythe example demonstrates how to obtain an individual count from the list using the get(function choose runrun module python shell window opensand you see the results of using the counter objectas shown in figure -
9,653
figure - the counter is helpful in obtaining statistics about longer lists notice that the information is actually stored in the counter as key and value pair discusses this topic in greater detail all you really need to know for now is that the element found in mylist becomes key in listcount that identifies the unique element name the value contains the number of times that that element appears within mylist
9,654
collecting all sorts of data in this defining collection using tuples using dictionaries developing stacks using lists using the queue module using the deque module eople collect all sorts of things the cds stacked near your entertainment centerthe plates that are part of seriesbaseball cardsand even the pens from every restaurant you've ever visited are all collections the collections you encounter when you write applications are the same as the collections in the real world collection is simply grouping of like items in one place and usually organized into some easily understood form this is about collections of various sorts the central idea behind every collection is to create an environment in which the collection is properly managed and lets you easily locate precisely what you want at any given time set of bookshelves works great for storing booksdvdsand other sorts of flat items howeveryou probably put your pen collection in holder or even display case the difference in storage locations doesn' change the fact that both house collections the same is true with computer collections yesthere are differences between stack and queuebut the main idea is to provide the means to manage data properly and make it easy to access when needed understanding collections in you're introduced to sequences sequence is succession of values that are bound together in container the simplest sequence is stringwhich is succession of characters next comes the list described in which is succession of objects even though string and list are both sequencesthey have significant differences for examplewhen working with stringyou set all the characters to lowercase -something
9,655
you can' do with list on the other handlists let you append new itemswhich is something string doesn' support collections are simply another kind of sequencealbeit more complex sequence than you find in either string or list no matter which sequence you usethey all support two functionsindex(and count(the index(function always returns the position of specified item in the sequence for exampleyou can return the position of character in string or the position of an object in list the count(function returns the number of times specific item appears in the list againthe kind of specific item depends upon the kind of sequence you can use collections to create database-like structures using python each collection type has different purposeand you use the various types in specific ways the important idea to remember is that collections are simply another kind of sequence as with every other kind of sequencecollections always support the index(and count(functions as part of their base functionality python is designed to be extensible howeverit does rely on base set of collections that you can use to create most application types this describes the most common collectionstuplea tuple is collection used to create complex list-like sequences an advantage of tuples is that you can nest the content of tuple this feature lets you create structures that can hold employee records or - coordinate pairs dictionaryas with the real dictionariesyou create key/value pairs when using the dictionary collection (think of word and its associated definitiona dictionary provides incredibly fast search times and makes ordering data significantly easier stackmost programming languages support stacks directly howeverpython doesn' support the stackalthough there' work-around for that stack is first in/first out (fifosequence think of pile of pancakesyou can add new pancakes to the top and also take them off of the top stack is an important collection that you can simulate in python using listwhich is precisely what this does queuea queue is last in/first out (lifocollection you use it to track items that need to be processed in some way think of queue as line at the bank you go into the linewait your turnand are eventually called to talk with teller dequea double-ended queue (dequeis queue-like structure that lets you add or remove items from either endbut not from the middle you can use deque as queue or stack or any other kind of collection to which you're adding and from which you're removing items in an orderly manner (in contrast to liststuplesand dictionarieswhich allow randomized access and management
9,656
working with tuples as previously mentioneda tuple is collection used to create complex listsin which you can embed one tuple within another this embedding lets you create hierarchies with tuples hierarchy could be something as simple as the directory listing of your hard drive or an organizational chart for your company the idea is that you can create complex data structures using tuple tuples are immutablewhich means you can' change them you can create new tuple with the same name and modify it in some waybut you can' modify an existing tuple lists are mutablewhich means that you can change them soa tuple can seem at first to be at disadvantagebut immutability has all sorts of advantagessuch as being more secure as well as faster in additionimmutable objects are easier to use with multiple processors the two biggest differences between tuple and list are that tuple is immutable and allows you to embed one tuple inside another the following steps demonstrate how you can interact with tuple in python open python shell window you see the familiar python prompt type mytuple ("red""blue""green"and press enter python creates tuple containing three strings type mytuple and press enter you see the content of mytuplewhich is three stringsas shown in figure - notice that the entries use single quoteseven though you used double quotes to create the tuple in additionnotice that tuple uses parentheses rather than square bracketsas lists do figure - tuples use parenthe sesnot square brackets
9,657
type dir(mytupleand press enter python presents list of functions that you can use with tuplesas shown in figure - notice that the list of functions appears significantly smaller than the list of functions provided with lists in the count(and index(functions are present figure - fewer functions seem to be available for use with tuples howeverappearances can be deceiving for exampleyou can add new items using the __add__(function when working with python objectslook at all the entries before you make decision as to functionality type mytuple mytuple __add__(("purple",)and press enter this code adds new tuple to mytuple and places the result in new copy of mytuple the old copy of mytuple is destroyed after the call the __add__(function accepts only tuples as input this means that you must enclose the addition in parentheses in additionwhen creating tuple with single entryyou must add comma after the entryas shown in the example this is an odd python rule that you need to keep in mind or you'll see an error message similar to this onetypeerrorcan only concatenate tuple (not "str"to tuple type mytuple and press enter the addition to mytuple appears at the end of the listas shown in figure - notice that it appears at the same level as the other entries
9,658
figure - this new copy of mytuple contains an additional entry type mytuple mytuple __add__(("yellow"("orange""black"))and press enter this step adds three entriesyelloworangeand black howeverorange and black are added as tuple within the main tuplewhich creates hierarchy these two entries are actually treated as single entry within the main tuple you can replace the __add__(function with the concatenation operator for exampleif you want to add magenta to the front of the tuple listyou type mytuple ("magenta",mytuple type mytuple[ and press enter python displays single member of mytupleorange tuples use indexes to access individual membersjust as lists do you can also specify range when needed anything you can do with list index you can also do with tuple index type mytuple[ and press enter you see tuple that contains orange and black of courseyou might not want to use both members in tuple form tuples do contain hierarchies on regular basis you can detect when an index has returned another tuplerather than valueby testing for type for examplein this caseyou could detect that the sixth item (index contains tuple by typing type(mytuple[ ]=tuple the output would be true in this case
9,659
type mytuple[ ][ and press enter at this pointyou see orange as output figure - shows the results of the previous three commands so that you can see the progression of index usage the indexes always appear in order of their level in the hierarchy figure - use indexes to gain access to the indi vidual tuple members using combination of indexes and the __add__(function (or the concatenation operator+)you can create flexible applications that rely on tuples for exampleyou can remove an element from tuple by making it equal to range of values if you wanted to remove the tuple containing orange and blackyou type mytuple mytuple[ : working with dictionaries python dictionary works just the same as its real-world counterpart -you create key and value pair it' just like the word and definition in dictionary as with listsdictionaries are mutablewhich means that you can change
9,660
them as needed the main reason to use dictionary is to make information lookup faster the key is always short and unique so that the computer doesn' spend lot of time looking for the information you need the following sections demonstrate how to create and use dictionary when you know how to work with dictionariesyou use that knowledge to make up for deficiencies in the python language most languages include the concept of switch statementwhich is essentially menu of choices from which one choice is selected python doesn' include this optionso you must normally rely on if elif statements to perform the task (such statements workbut they aren' as clear as they could be creating and using dictionary creating and using dictionary is much like working with listexcept that you must now define key and value pair here are the special rules for creating keythe key must be unique when you enter duplicate keythe information found in the second entry wins -the first entry is simply replaced with the second the key must be immutable this rule means that you can use stringsnumbersor tuples for the key you can'thoweveruse list for key you have no restrictions on the values you provide value can be any python objectso you can use dictionary to access an employee record or other complex data the following steps help you understand how to use dictionaries better open python shell window you see the familiar python prompt type colors {"sam""blue""amy""red""sarah""yellow"and press enter python creates dictionary containing three entries with people' favorite colors notice how you create the key and value pair the key comes firstfollowed by colon and then the value each entry is separated by comma type colors and press enter you see the key and value pairsas shown in figure - howevernotice that the entries are sorted in key order dictionary automatically keeps the keys sorted to make access fasterwhich means that you get fast
9,661
search times even when working with large data set the downside is that creating the dictionary takes longer than using something like list because the computer is busy sorting the entries figure - diction ary places entries in sorted order type colors["sarah"and press enter you see the color associated with sarahyellowas shown in figure - using string as keyrather than using numeric indexmakes the code easier to read and makes it self-documenting to an extent by making your code more readabledictionaries save you considerable time in the long run (which is why they're so popularhoweverthe convenience of dictionary comes at the cost of additional creation time and higher use of resourcesso you have trade-offs to consider figure - dictionaries make value access easy and selfdocumenting type colors keysand press enter the dictionary presents list of the keys it containsas shown in figure - you can use these keys to automate access to the dictionary
9,662
figure - you can ask dictionary for list of keys type the following code (pressing enter after each line and pressing enter twice after the last line)for item in colors keys()print("{ likes the color { format(itemcolors[item])the example code outputs listing of each of the user names and the user' favorite coloras shown in figure - using dictionaries can make creating useful output lot easier the use of meaningful key means that the key can easily be part of the output figure - you can create useful keys to output information with greater ease
9,663
type colors["sarah""purpleand press enter the dictionary content is updated so that sarah now likes purple instead of yellow type colors update({"harry""orange"}and press enter new entry is added to the dictionary place your cursor at the end of the third line of the code you typed in step and press enter the editor creates copy of the code for you this is time-saving technique that you can use in the python shell when you experiment while using code that takes while to type even though you have to type it the first timeyou have no good reason to type it the second time press enter twice you see the updated output in figure - notice that harry is added in sorted order in additionsarah' entry is changed to the color purple figure - dictionaries are easy to modify
9,664
type del colors["sam"and press enter python removes sam' entry from the dictionary repeat steps and you verify that sam' entry is actually gone type len(colorsand press enter the output value of verifies that the dictionary contains only three entries nowrather than type colors clearand press enter type len(colorsand press enter python reports that colors has entriesso the dictionary is now empty close the python shell window replacing the switch statement with dictionary most programming languages provide some sort of switch statement switch statement provides for elegant menu type selections the user has number of options but is allowed to choose only one of them the program takes some course of action based on the user selection here is some representative code (it won' executeof switch statement you might find in another languageswitch(ncase print("you selected blue ")breakcase print("you selected yellow ")breakcase print("you selected green ")breakthe application normally presents menu-type interfaceobtains the number of the selection from the userand then chooses the correct course of action from the switch statement it' straightforward and much neater than using series of if statements to accomplish the same task
9,665
unfortunatelypython doesn' come with switch statement the best you can hope to do is use an if elif statement for the task howeverby using dictionaryyou can simulate the use of switch statement the following steps help you create an example that will demonstrate the required technique this example also appears with the downloadable source code as pythonswitch py open python file window you see an editor in which you can type the example code type the following code into the window -pressing enter after each linedef printblue()print("you chose blue!\ \ "def printred()print("you chose red!\ \ "def printorange()print("you chose orange!\ \ "def printyellow()print("you chose yellow!\ \ "before the code can do anything for youyou must define the tasks each of these functions defines task associated with selecting color option onscreen only one of them gets called at any given time type the following code into the window -pressing enter after each linecolorselect printblue printred printorange printyellow this code is the dictionary each key is like the case part of the switch statement the values specify what to do in other wordsthis is the switch structure the functions that you created earlier are the action part of the switch -the part that goes between the case statement and the break clause
9,666
type the following code into the window -pressing enter after each lineselection while (selection ! )print(" blue"print(" red"print(" orange"print(" yellow"print(" quit"selection int(input("select color option")if (selection > and (selection )colorselect[selection](finallyyou see the user interface part of the example the code begins by creating an input variableselection it then goes into loop until the user enters value of during each loopthe application displays list of options and then waits for user input when the user does provide inputthe application performs range check on it any value between and selects one of the functions defined earlier using the dictionary as the switching mechanism choose runrun module you see python shell window open the application displays menu like the one shown in figure - figure - the application begins by displaying the menu
9,667
type and press enter the application tells you that you selected blue and then displays the menu againas shown in figure - figure - after dis playing your selectionthe applica tion displays the menu again type and press enter the application ends creating stacks using lists stack is handy programming structure because you can use it to save an application execution environment (the state of variables and other attributes of the application environment at any given timeor as means of determining an order of execution unfortunatelypython doesn' provide stack as collection howeverit does provide listsand you can use list as perfectly acceptable stack the following steps help you create an example of using list as stack this example also appears with the downloadable source code as liststack py
9,668
open python file window you see an editor in which you can type the example code type the following code into the window -pressing enter after each linemystack [stacksize def displaystack()print("stack currently contains:"for item in mystackprint(itemdef push(value)if len(mystackstacksizemystack append(valueelseprint("stack is full!"def pop()if len(mystack mystack pop(elseprint("stack is empty "push( push( push( displaystack(input("press any key when ready "push( displaystack(input("press any key when ready "pop(displaystack(input("press any key when ready "pop(pop(pop(displaystack(
9,669
in this examplethe application creates list and variable to determine the maximum stack size stacks normally have specific size range this is admittedly really small stackbut it serves well for the example' needs stacks work by pushing value onto the top of the stack and popping values back off the top of the stack the push(and pop(functions perform these two tasks the code adds displaystack(to make it easier to see the stack content as needed the remaining code exercises the stack (demonstrates its functionalityby pushing values onto it and then removing them there are four main exercise sections that test stack functionality choose runrun module you see python shell window open the application fills the stack with information and then displays it onscreenas shown in figure - in this case is at the top of the stack because it' the last value added figure - stack pushes values one on top of the other press enter the application attempts to push another value onto the stack howeverthe stack is fullso the task failsas shown in figure - press enter the application pops value from the top of the stack remember that is the top of the stackso that' the value that is missing in figure -
9,670
figure - when the stack is fullit can' accept any more values figure - popping value means removing it from the top of the stack press enter the application tries to pop more values from the stack than it containsresulting in an erroras shown in figure - any stack implementation that you create must be able to detect both overflows (too many entriesand underflows (too few entries
9,671
figure - make sure that your stack imple mentation detects overflows and underflows working with queues queue works differently from stack think of any line you've ever stood inyou go to the back of the lineand when you reach the front of the line you get to do whatever you stood in the line to do queue is often used for task scheduling and to maintain program flow -just as it is in the real world the following steps help you create queue-based application this example also appears with the downloadable source code as queuedata py open python file window you see an editor in which you can type the example code type the following code into the window -pressing enter after each lineimport queue myqueue queue queue( print(myqueue empty()input("press any key when ready "
9,672
myqueue put( myqueue put( print(myqueue full()input("press any key when ready "myqueue put( print(myqueue full()input("press any key when ready "print(myqueue get()print(myqueue empty()print(myqueue full()input("press any key when ready "print(myqueue get()print(myqueue get()to create queueyou must import the queue module this module actually contains number of queue typesbut this example uses only the standard fifo queue when queue is emptythe empty(function returns true likewisewhen queue is fullthe full(function returns true by testing the state of empty(and full()you can determine whether you need to perform additional work with the queue or whether you can add other information to it these two functions help you manage queue it' not possible to iterate through queue using for loop as you have done with other collection typesso you must monitor empty(and full(instead the two functions used to work with data in queue are put()which adds new dataand get()which removes data problem with queues is that if you try to put more items into the queue than it can holdit simply waits until space is available to hold it unless you're using multithreaded application (one that uses individual threads of execution to perform more than one task at one time)this state could end up freezing your application choose runrun module you see python shell window open the application tests the state of the queue in this caseyou see an output of truewhich means that the queue is empty press enter the application adds two new values to the queue in doing sothe queue is no longer emptyas shown in figure -
9,673
figure - when the application puts new entries in the queuethe queue no longer reports that it' empty press enter the application adds another entry to the queuewhich means that the queue is now full because it was set to size of this means that full(will return true because the queue is now full press enter to free space in the queuethe application gets one of the entries whenever an application gets an entrythe get(function returns that entry given that was the first value added to the queuethe print(function should return value of as shown in figure - in additionboth empty(and full(should now return false figure - monitoring is key part of work ing with queues press enter the application gets the remaining two entries you see and (in turnas output
9,674
working with deques deque is simply queue where you can remove and add items from either end in many languagesa queue or stack starts out as deque specialized code serves to limit deque functionality to what is needed to perform particular task when working with dequeyou need to think of the deque as sort of horizontal line certain individual functions work with the left and right ends of the deque so that you can add and remove items from either side the following steps help you create an example that demonstrates deque usage this example also appears with the downloadable source code as dequedata py open python file window you see an editor in which you can type the example code type the following code into the window -pressing enter after each line import collections mydeque collections deque("abcdef" print("starting state:"for item in mydequeprint(itemend="print("\ \ \ \nappending and extending right"mydeque append(" "mydeque extend("ij"for item in mydequeprint(itemend="print("\ \nmydeque contains { items format(len(mydeque))print("\ \npopping right"print("popping { }format(mydeque pop())for item in mydequeprint(itemend="print("\ \ \ \nappending and extending left"mydeque appendleft(" "mydeque extendleft("bc"for item in mydequeprint(itemend="print("\ \nmydeque contains { items format(len(mydeque))
9,675
print("\ \npopping left"print("popping { }format(mydeque popleft())for item in mydequeprint(itemend="print("\ \ \ \nremoving"mydeque remove(" "for item in mydequeprint(itemend="the implementation of deque is found in the collections moduleso you need to import it into your code when you create dequeyou can optionally specify starting list of iterable items (items that can be accessed and processed as part of loop structureand maximum sizeas shown deque differentiates between adding one item and adding group of items you use append(or appendleft(when adding single item the extend(and extendleft(functions let you add multiple items you use the pop(or popleft(functions to remove one item at time the act of popping values returns the value poppedso the example prints the value onscreen the remove(function is unique in that it always works from the left side and always removes the first instance of the requested data unlike some other collectionsa deque is fully iterable this means that you can obtain list of items using for loop whenever necessary choose runrun module you see python shell window open the example outputs the information shown in figure - it' important to follow the output listing closely notice how the size of the deque changes over time after the application pops the jthe deque still contains eight items when the application appends and extends from the leftit adds three more items howeverthe resulting deque contains only ten items when you exceed the maximum size of dequethe extra data simply falls off the other end
9,676
figure - deque provides the doubleended func tionality and other fea tures you' expect
9,677
9,678
creating and using classes in this defining the characteristics of class specifying the class components creating your own class working with the class in an application working with subclasses ou've already worked with number of classes in previous many of the examples are easy to construct and use because they depend on the python classes even though classes are briefly mentioned in previous those largely ignore them simply because discussing them wasn' immediately important classes make working with python code more convenient by helping to make your applications easy to readunderstandand use you use classes to create containers for your code and dataso they stay together in one piece outsiders see your class as black box -data goes in and results come out at some pointyou need to start constructing classes of your own if you want to avoid the dangers of the spaghetti code that is found in older applications spaghetti code is much as the name implies -various lines of procedures are interwoven and spread out in such way that it' hard to figure out where one piece of spaghetti begins and another ends trying to maintain spaghetti code is nearly impossibleand some organizations have thrown out applications because no one could figure them out besides helping you understand classes as packaging method that avoids spaghetti codethis helps you create and use your own classes for the first time you gain insights into how python classes work toward making your applications convenient to work with this is an introductory sort of thoughand you won' become so involved in classes that your head begins to spin around on its own this is about making class development simple and manageable
9,679
understanding the class as packaging method class is essentially method for packaging code the idea is to simplify code reusemake applications more reliableand reduce the potential for security breaches well-designed classes are black boxes that accept certain inputs and provide specific outputs based on those inputs in shorta class shouldn' create any surprises for anyone and should have known (quantifiablebehaviors how the class accomplishes its work is unimportantand hiding the details of its inner workings is essential to good coding practice before you move onto actual class theoryyou need to know few terms that are specific to classes the following list defines terms that you need to know in order to use the material that follows later in the these terms are specific to python (other languages may use different terms for the same techniques or define terms that python uses in different ways classdefines blueprint for creating an object think of builder who wants to create building of some type the builder uses blueprint to ensure that the building will meet the required specifications likewisepython uses classes as blueprint for creating new objects class variableprovides storage location used by all methods in an instance of the class class variable is defined within the class proper but outside of any of the class methods class variables aren' used very often because they're potential security risk -every method of the class has access to the same information in addition to being security riskclass variables are also visible as part of the class rather than particular instance of classso they pose the potential problem of class contamination data memberdefines either class variable or an instance variable used to hold data associated with class and its objects function overloadingcreates more than one version of functionwhich results in different behaviors the essential task of the function may be the samebut the inputs are different and potentially the outputs as well function overloading is used to provide flexibility so that function can work with applications in various ways inheritanceuses parent class to create child classes that have the same characteristics the child classes usually have extended functionality or provide more specific behaviors than the parent class does instancedefines an object created from the specification provided by class python can create as many instances of class to perform the work required by an application each instance is unique
9,680
instance variableprovides storage location used by single method of an instance of class the variable is defined within method instance variables are considered safer than class variables because only one method of the class can access them data is passed between methods using argumentswhich allows for controlled checks of incoming data and better control over data management instantiationperforms the act of creating an instance of class the resulting object is unique class instance methoddefines the term used for functions that are part of class even though function and method essentially define the same elementmethod is considered more specific because only classes can have methods objectdefines unique instance of class the object contains all the methods and properties of the original class howeverthe data for each object differs the storage locations are uniqueeven if the data is the same operator overloadingcreates more than one version of function that is associated with an operator such as+-/or *which results in different behaviors the essential task of the operator may be the samebut the way in which the operator interacts with the data differs operator overloading is used to provide flexibility so that an operator can work with applications in various ways considering the parts of class class has specific construction each part of class performs particular task that gives the class useful characteristics of coursethe class begins with container that is used to hold the entire class togetherso that' the part that the first section that follows discusses the remaining sections describe the other parts of class and help you understand how they contribute to the class as whole creating the class definition class need not be particularly complex in factyou can create just the container and one class element and call it class of coursethe resulting class won' do muchbut you can instantiate it (tell python to build an object using your class as blueprintand work with it as you would any other class the following steps help you understand the basics behind class by creating the simplest class possible
9,681
open python shell window you see the familiar python prompt type the following code (pressing enter after each line and pressing enter twice after the last line)class myclassmyvar the first line defines the class containerwhich consists of the keyword class and the class namewhich is myclass every class you create must begin precisely this way you must always include class followed by the class name the second line is the class suite all the elements that comprise the class are called the class suite in this caseyou see class variable named myvarwhich is set to value of every instance of the class will have the same variable and start at the same value type myinstance myclassand press enter you have just created an instance of myclass named myinstance of courseyou'll want to verify that you really have created such an instance step accomplishes that task type myinstance myvar and press enter the output of as shown in figure - demonstrates that myinstance does indeed have class variable named myvar figure - the instance contains the required variable type myinstance __class__ and press enter python displays the class used to create this instanceas shown in figure - the output tells you that this class is part of the __main__ modulewhich means that you typed it directly into the shell
9,682
retain this window and class for the next section figure - the class name is also correctso you know that this instance is cre ated using myclass considering the built-in class attributes when you create classyou can easily think that all you get is the class howeverpython adds built-in functionality to your class for examplein the preceding sectionyou type __class__ and press enter the __class__ attribute is built inyou didn' create it it helps to know that python provides this functionality so that you don' have to add it the functionality is needed often enough that every class should have itso python supplies it the following steps help you work with the built-in class attributes use the python shell window that you open in the preceding section if you haven' followed the steps in the preceding section"creating the class definition,please do so now type dir(myinstanceand press enter list of attributes appearsas shown in figure - these attributes provide specific functionality for your class they're also common to every other class you createso you can count on always having this functionality in the classes you create type help('__class__'and press enter python displays information on the __class__ attributeas shown in figure - you can use the same technique for learning more about any attribute that python adds to your class close the python shell window
9,683
figure - use the dir(function to determine which builtin attributes are present figure - python provides help for each of the attributes it adds to your class
9,684
working with methods methods are simply another kind of function that reside in classes you create and work with methods in precisely the same way that you do functionsexcept that methods are always associated with class (you don' see freestanding methods as you do functionsyou can create two kinds of methodsthose associated with the class itself and those associated with an instance of class it' important to differentiate between the two the following sections provide the details needed to work with both creating class methods class method is one that you execute directly from the class without creating an instance of the class sometimes you need to create methods that execute from the classsuch as the functions you used with the str class in order to modify strings as an examplethe multipleexception py example in uses the str upper(function the following steps demonstrate how to create and use class method open python shell window you see the familiar python prompt type the following code (pressing enter after each line and pressing enter twice after the last line)class myclassdef sayhello()print("hello there!"the example class contains single defined attributesayhello(this method doesn' accept any arguments and doesn' return any values it simply prints message as output howeverthe method works just fine for demonstration purposes type myclass sayhello(and press enter the example outputs the expected stringas shown in figure - notice that you didn' need to create an instance of the class -the method is available immediately for use close the python shell window
9,685
figure - the class method outputs simple message class method can work only with class data it doesn' know about any data associated with an instance of the class you can pass it data as an argumentand the method can return information as neededbut it can' access the instance data as consequenceyou need to exercise care when creating class methods to ensure that they're essentially self-contained creating instance methods an instance method is one that is part of the individual instances you use instance methods to manipulate the data that the class manages as consequenceyou can' use instance methods until you instantiate an object from the class all instance methods accept single argument as minimumself the self argument points at the particular instance that the application is using to manipulate data without the self argumentthe method wouldn' know which instance data to use howeverself isn' considered an accessible argument -the value for self is supplied by pythonand you can' change it as part of calling the method the following steps demonstrate how to create and use instance methods in python open python shell window you see the familiar python prompt type the following code (pressing enter after each line and pressing enter twice after the last line)class myclassdef sayhello(self)print("hello there!"
9,686
the example class contains single defined attributesayhello(this method doesn' accept any special arguments and doesn' return any values it simply prints message as output howeverthe method works just fine for demonstration purposes type myinstance myclassand press enter python creates an instance of myclass named myinstance type myinstance sayhelloand press enter you see the message shown in figure - figure - the instance message is called as part of an object and outputs this simple message close the python shell window working with constructors constructor is special kind of method that python calls when it instantiates an object using the definitions found in your class python relies on the constructor to perform tasks such as initializing (assigning values toany instance variables that the object will need when it starts constructors can also verify that there are enough resources for the object and perform any other start-up task you can think of the name of constructor is always the same__init__(the constructor can accept arguments when necessary to create the object when you create class without constructorpython automatically creates default constructor for you that doesn' do anything every class must have constructoreven if it simply relies on the default constructor the following steps demonstrate how to create constructor
9,687
open python shell window you see the familiar python prompt type the following code (pressing enter after each line and pressing enter twice after the last line)class myclassgreeting "def __init__(selfname="there")self greeting name "!def sayhello(self)print("hello { }format(self greeting)this example provides your first example of function overloading in this casethere are two versions of __init__(the first doesn' require any special input because it uses the default value for the name of "therethe second requires name as an input it sets greeting to the value of this nameplus an exclamation mark the sayhello(method is essentially the same as previous examples in this python doesn' support true function overloading many strict adherents to strict object-oriented programming (oopprinciples consider default values to be something different from function overloading howeverthe use of default values obtains the same resultand it' the only option that python offers in true function overloadingyou see multiple copies of the same functioneach of which could process the input differently type myinstance myclassand press enter python creates an instance of myclass named myinstance type myinstance sayhelloand press enter you see the message shown in figure - notice that this message provides the defaultgeneric greeting type myinstance myclass("amy"and press enter python creates an instance of myclass named myinstance type myinstance sayhelloand press enter you see the message shown in figure - notice that this message provides specific greeting close the python shell window
9,688
figure - the first ver sion of the constructor provides default value for the name figure - supplying the con structor with name provides customized output working with variables as mentioned earlier in the bookvariables are storage containers that hold data when working with classesyou need to consider how the data is stored and managed class can include both class variables and instance variables the class variables are defined as part of the class itselfwhile instance variables are defined as part of methods the following sections show how to use both variable types
9,689
creating class variables class variables provide global access to data that your class manipulates in some way in most casesyou initialize global variables using the constructor to ensure that they contain known good value the following steps demonstrate how class variables work open python shell window you see the familiar python prompt type the following code (pressing enter after each line and pressing enter twice after the last line)class myclassgreeting "def sayhello(self)print("hello { }format(self greeting)this is version of the code found in the "working with constructorssection of the but this version doesn' include the constructor normally you do include constructor to ensure that the class variable is initialized properly howeverthis series of steps shows how class variables can go wrong type myclass greeting "zeldaand press enter this statement sets the value of greeting to something other than the value that you used when you created the class of courseanyone could make this change the big question is whether the change will take type myclass greeting and press enter you see that the value of greeting has changedas shown in figure - type myinstance myclassand press enter python creates an instance of myclass named myinstance figure - you can change the value of greeting
9,690
type myinstance sayhelloand press enter you see the message shown in figure - the change that you made to greeting has carried over to the instance of the class it' true that the use of class variable hasn' really caused problem in this examplebut you can imagine what would happen in real application if someone wanted to cause problems this is just simple example of how class variables can go wrong the two concepts you should take away from this example are as followsavoid class variables when you can because they're inherently unsafe always initialize class variables to known good value in the constructor code close the python shell window figure - the change to greeting carries over to the instance of the class creating instance variables instance variables are always defined as part of method the input arguments to method are considered instance variables because they exist only when the method exists using instance variables is usually safer than using class variables because it' easier to maintain control over them and to ensure that the caller is providing the correct input the following steps show an example of using instance variables
9,691
open python shell window you see the familiar python prompt type the following code (pressing enter after each line and pressing enter twice after the last line)class myclassdef doadd(selfvalue = value = )sum value value print("the sum of { plus { is { format(value value sum)in this caseyou have three instance variables the input argumentsvalue and value have default values of so doadd(can' fail simply because the user forgot to provide values of coursethe user could always supply something other than numbersso you should provide the appropriate checks as part of your code the third instance variable is sumwhich is equal to value value the code simply adds the two numbers together and displays the result type myinstance myclassand press enter python creates an instance of myclass named myinstance type myinstance doadd( and press enter you see the message shown in figure - in this caseyou see the sum of adding and figure - the output is simply the sum of two numbers close the python shell window
9,692
using methods with variable argument lists sometimes you create methods that can take variable number of arguments handling this sort of situation is something python does well here are the two kinds of variable arguments that you can create*argsprovides list of unnamed arguments **kwargsprovides list of named arguments the actual names of the arguments don' matterbut python developers use *args and **kwargs as convention so that other python developers know that they're variable list of arguments notice that the first variable argument has just one asterisk (*associated with itwhich means the arguments are unnamed the second variable has two asteriskswhich means that the arguments are named the following steps demonstrate how to use both approaches to writing an application this example also appears with the downloadable source code as variableargs py open python file window you see an editor in which you can type the example code type the following code into the window -pressing enter after each lineclass myclassdef printlist (*args)for countitem in enumerate(args)print("{ { }format(countitem)def printlist (**kwargs)for namevalue in kwargs items()print("{ likes { }format(namevalue)myclass printlist ("red""blue""green"myclass printlist (george="red"sue="blue"zarah="green"for the purposes of this exampleyou're seeing the arguments implemented as part of class method howeveryou can use them just as easily with an instance method look carefully at printlist (and you see new method of using for loop to iterate through list in this casethe enumerate(function outputs both count (the loop countand the string that was passed to the function
9,693
the printlist (function accepts dictionary input just as with printlist ()this list can be any length howeveryou must process the items(found in the dictionary to obtain the individual values choose runrun module you see the output shown in figure - the individual lists can be of any length in factin this situationplaying with the code to see what you can do with it is good idea for exampletry mixing numbers and strings with the first list to see what happens try adding boolean values as well the point is that using this technique makes your methods incredibly flexible if all you want is list of values as input figure - the code can process any number of entries in the list overloading operators in some situationsyou want to be able to do something special as the result of using standard operator such as add (+in factsometimes python doesn' provide default behavior for operators because it has no default to implement no matter what the reason might beoverloading operators makes it possible to assign new functionality to existing operators so that they do what you wantrather than what python intended the following steps demonstrate how to overload an operator and use it as part of an application this example also appears with the downloadable source code as overloadoperator py open python file window you see an editor in which you can type the example code
9,694
type the following code into the window -pressing enter after each lineclass myclassdef __init__(self*args)self input args def __add__(selfother)output myclass(output input self input other input return output def __str__(self)output "for item in self inputoutput +item output +return output value myclass("red""green""blue"value myclass("yellow""purple""cyan"value value value print("{ { { }format(value value value )the example demonstrates few different techniques the constructor__init__()demonstrates method for creating an instance variable attached to the self object you can use this approach to create as many variables as needed to support the instance when you create your own classesno operator is defined until you define onein most cases the only exception is when you inherit from an existing class that already has the operator defined (see the "extending classes to make new classessectionlater in this for detailsin order to add two myclass entries togetheryou must define the __add__(methodwhich equates to the operator the code used for the __add__(method may look little oddtoobut you need to think about it one line at time the code begins by creating new objectoutputfrom myclass nothing is added to output at this point -it' blank object the two objects that you want to addself input and other inputare actually tuples (see "working with tuples,in for more details about tuples the code places the sum of these two objects into output input the __add__(method then returns the new combined object to the caller
9,695
of courseyou may want to know why you can' simply add the two inputs together as you would number the answer is that you' end up with tuple as an outputrather than myclass as an output the type of the output would be changedand that would also change any use of the resulting object to print myclass properlyyou also need to define __str__(method this method converts myclass object into string in this casethe output is space-delimited string (in which each of the items in the string is separated from the other items by spacecontaining each of the values found in self input of coursethe class that you create can output any string that fully represents the object the main procedure creates two test objectsvalue and value it adds them together and places the result in value the result is printed onscreen choose runrun module figure - shows the result of adding the two objects togetherconverting them to stringsand then printing the result it' lot of code for such simple output statementbut the result definitely demonstrates that you can create classes that are self-contained and fully functional figure - the result of adding two myclass objects is third object of the same type creating class all the previous material in this has helped prepare you for creating an interesting class of your own in this caseyou create class that you place into an external module and eventually access within an application listing - shows the code that you need to create the class this example also appears with the downloadable source code as myclass py
9,696
listing - creating an external class class myclassdef __init__(selfname="sam"age= )self name name self age age def getname(self)return self name def setname(selfname)self name name def getage(self)return self age def setage(selfage)self age age def __str__(self)return "{ is aged { format(self nameself agein this casethe class begins by creating an object with two instance variablesname and age if the user fails to provide these valuesthey default to sam and this example provides you with new class feature most developers call this feature an accessor essentiallyit provides access to an underlying value there are two types of accessorsgetters and setters both getname(and getage(are getters they provide read-only access to the underlying value the setname(and setage(methods are setterswhich provide writeonly access to the underlying value using combination of methods like this allows you to check inputs for correct type and rangeas well as verify that the caller has permission to view the information as with just about every other class you createyou need to define the __str__(method if you want the user to be able to print the object in this casethe class provides formatted output that lists both of the instance variables using the class in an application most of the timeyou use external classes when working with python it isn' very often that class exists within the confines of the application file because the application would become large and unmanageable in addition
9,697
reusing the class code in another application would be difficult the following steps help you use the myclass class that you created in the previous section this example also appears with the downloadable source code as myclasstest py open python file window you see an editor in which you can type the example code type the following code into the window -pressing enter after each lineimport myclass samsrecord myclass myclass(amysrecord myclass myclass("amy" print(samsrecord getage()samsrecord setage( print(amysrecord getname()amysrecord setname("aimee"print(samsrecordprint(amysrecordthe example code begins by importing the myclass module the module name is the name of the file used to store the external codenot the name of the class single module can contain multiple classesso always think of the module as being the actual file that is used to hold one or more classes that you need to use with your application after the module is importedthe application creates two myclass objects notice that you use the module name firstfollowed by the class name the first objectsamsrecorduses the default settings the second objectamysrecordrelies on custom settings sam has become year old after the application verifies that the age does need to be updatedit updates sam' age somehowhr spelled aimee' name wrong it turns out that amy is an incorrect spelling againafter the application verifies that the name is wrongit makes correction to amysrecord the final step is to print both records in their entirety choose runrun module the application displays series of messages as it puts myclass through its pacesas shown in figure - at this pointyou know all the essentials of creating great classes
9,698
figure - the output shows that the class is fully functional extending classes to make new classes as you might imaginecreating fully functionalproduction-grade class (one that is used in real-world application actually running on system that is accessed by usersis time consuming because real classes perform lot of tasks fortunatelypython supports feature called inheritance by using inheritanceyou can obtain the features you want from parent class when creating child class overriding the features that you don' need and adding new features lets you create new classes relatively fast and with lot less effort on your part in additionbecause the parent code is already testedyou don' have to put quite as much effort into ensuring that your new class works as expected the following sections show how to build and use classes that inherit from each other building the child class parent classes are normally supersets of something for exampleyou might create parent class named car and then create child classes of various car types around it in this caseyou build parent class named animal and use it to define child class named chicken of courseyou can easily add other child classes after you have animal in placesuch as gorilla class howeverfor this exampleyou build just the one parent and one child classas shown in listing - this example also appears with the downloadable source code as animals py
9,699
listing - building parent and child class class animaldef __init__(selfname=""age= type="")self name name self age age self type type def getname(self)return self name def setname(selfname)self name name def getage(self)return self age def setage(selfage)self age age def gettype(self)return self type def settype(selftype)self type type def __str__(self)return "{ is { aged { }format(self nameself typeself ageclass chicken(animal)def __init__(selfname=""age= )self name name self age age self type "chickendef settype(selftype)print("sorry{ will always be { }format(self nameself type)def makesound(self)print("{ says cluckcluckcluck!format(self name)