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 "creat... |
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 preven... |
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 ... |
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 value... |
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 t... |
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 ... |
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 y... |
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 t... |
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 th... |
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 pagesimpl... |
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 p... |
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 si... |
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 numbersn... |
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... |
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 pres... |
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 i... |
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 l... |
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 vert... |
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 a... |
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 co... |
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 wi... |
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 on... |
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... |
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 us... |
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 ... |
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(sear... |
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 o... |
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<lef... |
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 dec... |
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... |
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 programmi... |
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... |
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 l... |
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... |
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... |
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 ... |
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 lis... |
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 cl... |
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 ed... |
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... |
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... |
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 use... |
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 ... |
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 co... |
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 howe... |
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 ar... |
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="prin... |
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 collec... |
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 uniqu... |
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 ever... |
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(functio... |
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 compa... |
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... |
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 singl... |
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 usin... |
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 u... |
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 sarahyello... |
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 show... |
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 cr... |
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 p... |
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... |
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 ... |
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 ... |
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("... |
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... |
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 b... |
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 f... |
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 mod... |
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 sp... |
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... |
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 s... |
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... |
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 i... |
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 check... |
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... |
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 ... |
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 asso... |
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 car... |
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 myin... |
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 fir... |
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... |
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 fam... |
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 ... |
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 variable... |
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 argument... |
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 situationplay... |
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""b... |
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 nee... |
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 caseth... |
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... |
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 tas... |
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(selfty... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.