id int64 0 25.6k | text stringlengths 0 4.59k |
|---|---|
8,500 | what are design patternssitting at your desk in front of your workstationyou stare into spacetrying to figure out how to write new program feature you know intuitively what must be donewhat data and what objects come into playbut you have this underlying feeling that there is more elegant and general way to write this ... |
8,501 | what are design patternsview controller data model figure - model-view-controller illustration each of these aspects of the problem is separate objectand each has its own rules for managing its data communication among the userthe guiand the data should be carefully controlledand this separation of functions accomplish... |
8,502 | we see the same thing in programmingwhen we tell colleague how we accomplished tricky bit of programming so that they don' have to re-create it from scratch we simply recognize effective ways for objects to communicate while maintaining their own separate existences to summarizedesign patterns are frequently used algor... |
8,503 | what are design patternsthe examples in design patterns are brief and are written in either +orin some casessmalltalk if you are working in another languageit is helpful to have the pattern examples in your language of choice this part of the book attempts to fill that need for python programmers notes on object-orient... |
8,504 | at first this seems contrary to the customs of oo programmingbut you will see any number of cases among the design patterns where we find that inclusion of one or more objects inside another is the preferred method python design patterns the following discuss each of the design patterns featured in the design patterns ... |
8,505 | symbols (equal signsassignment (=operator initialization is equal to (==operator spacing abstract factory pattern consequences of - gardenmaker factory - github programs purposes of - thought questions user interfaces access (privileged)iterators - accessor methods accounts (github)setting up adapter pattern class adap... |
8,506 | adding command objectscontainers adding menusto windows - two numbersvisual programming command objectsmediators - anaconda consequences of and operator github programs arithmetic operators keyboard example - arithmetic/assignment statementscombined keymoderator class arrays undo button - references undo function - lis... |
8,507 | iterable containers switching between states iterator generator transitions for loops as iterators - strategy pattern modifying data consequences of - privileged access - context class using github programs command objects - line and bar graph strategies - consequences of plotstategy class - example system - program co... |
8,508 | behavioral patterns using - decorator pattern - visiting classes hello buttons visiting several classes - quit buttons - bitwise operators - radio buttons - blank linesclasses/functions red button blue buttoncreating undo buttoncommand pattern - boolean variables boss class composite pattern visitor pattern - bvacation... |
8,509 | listboxes - generators requests indentation sample code - inheritance - using instances character constants - creating check boxesdisabling singleton pattern - checkbox builder checkbuttonsgrid layouts - circleseeding class - class adapter class_init_method classes - isoscelestriangle classtemplate pattern keymoderator... |
8,510 | collections github programs lists changing contents - copying command-line arguments - execution commands creating interp command doubly linked lists - moving data between - program commandsstrategy pattern - slicing queuing spacing setsusing tuples comma-separated numbers comments docstrings returning indentation usin... |
8,511 | compound operatorsspacing listbox builder - comprehensionlists thought questions concrete methods factory method pattern - conditionscombining circleseeding class - console interfaceinterpreter pattern - event classes - constants seeding program - caseupper/lower character constants - named constants see variables gith... |
8,512 | data tables tree nodesinserting in data tables - treeview widget - decorator pattern buttons - consequences of - data types dataclass decorator - database classfacade pattern - decorated code - database objectsfacade pattern decorator class - databasescreating - github programs dataclass decorator - nonvisual decorator... |
8,513 | disabling check boxes errors dispatchingdouble catching - displaying handling images with pil selected securitiesbuilder pattern state data - dividing integers message boxescreating event classesfactory method pattern - exceptions docstrings handling double dispatchingvisitor pattern throwingsingleton pattern doubly li... |
8,514 | factory method pattern github programs java style formatting seeding program - numbers straight seeding class - using factory pattern building strings frameslabelframe widget - -string formatting functions factory classesoperation of - blank lines github programs calling gui caseupper/lower - math computations def keyw... |
8,515 | factory method pattern factory pattern flyweight pattern iconscreating - functions idle (integrated development and learning environment) interpreter pattern if statements iterator pattern mediator pattern memento pattern observer pattern programs prototype pattern proxy pattern pythondecision making python syntax sing... |
8,516 | interfaces interfaces internal iterators programming to iterable containers single interface mediators - iterator generator internal iterators for loops as iterators - interp command modifying data interpreter pattern privileged access - attrgetter operatorsorting - using consequences of - console interface - github pr... |
8,517 | continue statements listboxes chain of responsibility pattern - elif (else ifstatements - creating - format string function formatting lists changing contents - dates comprehension formattingc style copying formattingjava style creating -string formatting dictionaries numbers doubly linked listscomposite pattern - stri... |
8,518 | memento pattern graphics drawing program example - functions - variables - sample code - negative indexes using - nodes (leaf)composite pattern - menusadding to windows - nonvisual decorators - message boxes notificationsobserver pattern creating - numbers error message boxes addingvisual programming warning message bo... |
8,519 | objects pattern matching - buttoncommand objectscommand pattern command objects building - calling - pep standards pil (pillow image librarydisplaying images using - containers plotstategy classstrategy pattern - mediators and - pluggable adapters copy-on write objects point classtemplate pattern flyweight pattern poly... |
8,520 | python blank lines looping statements docstrings for loops indentation match function - naming conventions pattern matching - command-line arguments - print function - comments range functionarrays docstrings development - indentation development environments spacing anaconda complete programswriting - command-line exe... |
8,521 | match function - shortcutscreating - naming conventions - simple program example - range functionarrays starting programs - returning tuples statements starting python programs - break statements collections combined arithmetic/assignment statements decision making continue statements syntax elif (else ifstatements - g... |
8,522 | radio buttonscreating radio buttonscreating - radiobutton widget - range functionarrays reading files - reassigning variable values receiving help command - rectangles/squaresdrawing - recursive calls stetcomposite pattern red buttoncreating removing prefixes/suffixes from strings report generator exampleinterpreter pa... |
8,523 | squares/rectanglesdrawing - github programs standard trianglesdrawing line and bar graph strategies - starting python programs - plotstategy class - state datadisplaying - program commands - state pattern sample code - consequences of github programs using - strings graphics drawing program example - docstrings sample ... |
8,524 | structural patterns doubly linked lists - flyweightsdefined employee class - folders as flyweights - github programs github programs iterators selecting folders - leaf nodes - proxy pattern printing employee trees - comparing related patterns - recursive calls stet copy-on write objects salary computation github progra... |
8,525 | functions blank lines docstrings naming conventions - github programs integer division listsspacing loopsindentation operators table classfacade pattern tables creatingfacade pattern - data tables - combo boxes - listboxescreating - state datadisplaying - and operator tree nodesinserting in data tables - arithmetic ope... |
8,526 | about the tutorial audience prerequisites disclaimer copyright table of contents ii python overview history of python python features python environment local environment setup getting python installing python setting up path setting path at unix/linux setting path at windows python environment variables running python... |
8,527 | comments in python using blank lines waiting for the user multiple statements on single line multiple statement groups as suites command line arguments accessing command-line arguments parsing command-line arguments getopt getopt method exception getopt getopterror python variable types assigning values to variables mu... |
8,528 | python bitwise operators python logical operators python membership operators python identity operators python operators precedence python decision making if statement if else statement the elif statement single statement suites python loops while loop the infinite loop using else statement with loops single statement ... |
8,529 | python numbers number type conversion random number functions trigonometric functions mathematical constants python strings accessing values in strings updating strings escape characters string special operators string formatting operator triple quotes unicode string built-in string methods capitalize(method center(wid... |
8,530 | islower( isnumeric( isspace(method istitle( isupper( join(seq len(string ljust(width[fillchar] lower( lstrip( maketrans( max(str min(str replace(oldnew [max] rfind(strbeg= ,end=len(string) rindex(strbeg= end=len(string) rjust(width,[fillchar] rstrip( split(str=""num=string count(str) splitlines(num=string count('\ ') s... |
8,531 | zfill (width isdecimal( python lists python lists accessing values in lists updating lists deleting list elements basic list operations indexingslicingand matrixes built-in list functions and methods cmp(list list len(list max(list min(list list append(obj list count(obj list extend(seq list index(obj list insert(index... |
8,532 | accessing values in tuples updating tuples deleting tuple elements basic tuples operations indexingslicingand matrixes no enclosing delimiters built-in tuple functions cmp(tuple tuple len(tuple max(tuple min(tuple tuple(seg python dictionary accessing values in dictionary updating dictionary delete dictionary elements ... |
8,533 | dict get(key,default=none dict has_key(key dict items( dict keys( dict setdefault(keydefault=none dict update(dict dict values( python date and time what is tick what is timetuple getting current time getting formatted time getting calendar for month the time module time altzone time actime([tupletime] time clock time ... |
8,534 | time tzset( the calendar module other modules and functions python functions defining function calling function passing by reference versus passing by value function arguments required arguments keyword arguments default arguments variable length arguments the anonymous functions the return statement scope of variables... |
8,535 | the reload(function packages in python python files / printing to the screen reading keyboard input the raw_input function the input function opening and closing files the open function the file object attributes the close(method reading and writing files the write(method the read(method file positions renaming and del... |
8,536 | file flush( file fileno( file isatty( file next( file read([size] file readline([size] file readline([sizehint] file seek(offset[,whence] file tell( file truncate([size] file write(str file writelines(sequence os object methods python exceptions assertions in python the assert statement what is exception handling an ex... |
8,537 | overview of oop terminology creating classes creating instance objects accessing attributes built-in class attributes destroying objects (garbage collection class inheritance overriding methods base overloading methods overloading operators data hiding python regular expressions the match function the search function m... |
8,538 | web server support and configuration first cgi program http header cgi environment variables get and post methods passing information using get method simple url example get method simple form exampleget method passing information using post method passing checkbox data to cgi program passing radio button data to cgi p... |
8,539 | read operation update operation delete operation performing transactions commit operation rollback operation disconnecting database handling errors python network programming what is sockets the socket module server socket methods client socket methods general socket methods simple server simple client python internet ... |
8,540 | synchronizing threads multithreaded priority queue python xml processing what is xml xml parser architectures and apis parsing xml with sax apis the make_parser method the parse method the parsestring method parsing xml with dom apis python gui programming tkinter programming tkinter widgets button canvas checkbutton e... |
8,541 | scrollbar text toplevel spinbox panelwindow labelframe tkmessagebox standard attributes dimensions colors fonts anchors relief styles bitmaps cursors geometry management python tkinter pack(method python tkinter grid(method python tkinter place(method python further extensions pre-requisites for writing extensions firs... |
8,542 | the initialization function building and installing extensions importing extensions passing function parameters the pyarg_parsetuple function returning values the py_buildvalue function |
8,543 | python is high-levelinterpretedinteractive and object-oriented scripting language python is designed to be highly readable it uses english keywords frequently where as other languages use punctuationand it has fewer syntactical constructions than other languages python is interpretedpython is processed at runtime by th... |
8,544 | portablepython can run on wide variety of hardware platforms and has the same interface on all platforms extendableyou can add low-level modules to the python interpreter these modules enable programmers to add to or customize their tools to be more efficient databasespython provides interfaces to all major commercial ... |
8,545 | python is available on wide variety of platforms including linux and mac os let' understand how to set up our python environment local environment setup open terminal window and type "pythonto find out if it is already installed and which version is installed unix (solarislinuxfreebsdaixhp/uxsunosirixetc win /nt/ macin... |
8,546 | source code manually compiling the source code offers more flexibility in terms of choice of features that you require in your installation here is quick overview of installing python on various platformsunix and linux installation here are the simple steps to install python on unix/linux machine open web browser and g... |
8,547 | programs and other executable files can be in many directoriesso operating systems provide search path that lists the directories that the os searches for executables the path is stored in an environment variablewhich is named string maintained by the operating system this variable contains information available to the... |
8,548 | the python installer pythonstartup it contains the path of an initialization file containing python source code it is executed every time you start the interpreter it is named as pythonrc py in unix and it contains commands that load utilities or modify pythonpath pythoncaseok it is used in windows to instruct python t... |
8,549 | description - it provides debug output - it generates optimized bytecode (resulting in pyo files- do not run import site to look for python paths on startup - verbose output (detailed trace on import statements- disable class-based built-in exceptions (just use strings)obsolete starting with version - cmd file run pyth... |
8,550 | lambda functions assertions examplemake_html_skeleton py summary exercise modules modules and packages packages custom modules overview of python' standard library string handling command-line programming mathematics and numbers times and dates algorithms and collection data types file formatsencodingsand data persiste... |
8,551 | writing and reading binary data pickles with optional compression raw binary data with optional compression writing and parsing text files writing text parsing text parsing text using regular expressions writing and parsing xml files element trees dom (document object modelmanually writing xml parsing xml with sax (sim... |
8,552 | examplevalid py summary exercises debuggingtestingand profiling debugging dealing with syntax errors dealing with runtime errors scientific debugging unit testing profiling summary processes and threading using the multiprocessing module using the threading module examplea threaded find word program examplea threaded f... |
8,553 | exercises introduction to parsing bnf syntax and parsing terminology writing handcrafted parsers simple key-value data parsing playlist data parsing parsing the blocks domain-specific language pythonic parsing with pyparsing quick introduction to pyparsing simple key-value data parsing playlist data parsing parsing the... |
8,554 | python' keywords numeric operators and functions integer conversion functions integer bitwise operators the math module' functions and constants # the math module' functions and constants # python' string escapes string methods # string methods # string methods # list methods set methods and operators dictionary method... |
8,555 | regular expression quantifiers regular expression assertions the regular expression module' functions the regular expression module' flags regular expression object methods match object attributes and methods xvi |
8,556 | python is probably the easiest-to-learn and nicest-to-use programming language in widespread use python code is clear to read and writeand it is concise without being cryptic python is very expressive languagewhich means that we can usually write far fewer lines of python code than would be required for an equivalent a... |
8,557 | introduction the book' aim is to teach the python languageand although many of the standard python libraries are usednot all of them are this is not problembecause once you have read the bookyou will have enough python knowledge to be able to make use of any of the standard librariesor any third-party python libraryand... |
8,558 | possiblesmall but complete programs and modules are used as examples to provide realistic use cases the examplesexercise solutionsand the book' errata are available online at www qtrac eu/py book html two sets of examples are provided the standard examples work with any python version--use these if you care about pytho... |
8,559 | introduction built on procedural foundations--for examplemaking use of the same data typescollection data typesand control structures covers writing and reading files for binary filesthe coverage includes compression and random accessand for text filesthe coverage includes parsing manually and with regular expressions ... |
8,560 | typing python -vand if that does not work try python -vand failing that try python - if any of these work you now know that you already have python installedwhat version it isand what it is called (in this book we use the name python but use whatever name worked for youfor examplepython if you don' have any version of ... |
8,561 | introduction python' mailing list once the missing packages are installedrun /configure and make again after successfully makingyou could run make test to see that everything is okayalthough this is not necessary and can take many minutes to complete if you used --prefix to do local installationjust run make install fo... |
8,562 | phil thompson is python expert and the creator of pyqtprobably the best python gui library available phil' sharp-eyed and sometimes challenging feedback led to many clarifications and corrections trenton schulz is senior software engineer at nokia' qt software (formerly trolltechwho has been valuable reviewer of all my... |
8,563 | creating and running python programs python' "beautiful heartrapid introduction to procedural programming |||this provides enough information to get you started writing python programs we strongly recommend that you install python if you have not already done soso that you can get hands-on experience to reinforce what ... |
8,564 | rapid introduction to procedural programming tems ( linux and mac os xsome python applications have no extensionand python gui (graphical user interfaceprograms usually have an extension of pywparticularly on windows and mac os in this book we always use an extension of py for python console programs and python modules... |
8,565 | :\>cd :\py eg :\py eg\> :\python \python exe hello py since the cd (change directorycommand has an absolute pathit doesn' matter which directory you start out from unix users enter this instead (assuming that python is in the path)cd $home/py eg python hello py in both cases the output should be the samehello worldnote... |
8,566 | rapid introduction to procedural programming ('hello''world!'then it means that python is on the system and is being invoked instead of python one solution to this is to change the py file association from python to python the other (less convenientbut safersolution is to put the python interpreter in the path (assumin... |
8,567 | although the specific path may be different from the one shown if written using the second formthe first python interpreter found in the shell' current environment is used the second form is more versatile because it allows for the possibility that the python interpreter is not located in /usr/bin ( it could be in /usr... |
8,568 | rapid introduction to procedural programming figure idle' python shell prompts but idle is much easier to useso we recommend using idle for experimenting with code snippets the short interactive examples we show are all assumed to be entered in an interactive python interpreter or in idle' python shell we now know how ... |
8,569 | integers (positive and negative whole numbersusing the int typeand it represents strings (sequences of unicode charactersusing the str type here are some examples of integer and string literals- "infinitely demanding'simon critchley'positively abg /( )'incidentallythe second number shown is --the size of python' intege... |
8,570 | rapid introduction to procedural programming str( ' the int(conversion is tolerant of leading and trailing whitespaceso int( "would have worked just as well the str(conversion can be applied to almost any data item we can easily make our own custom data types support str(conversionand also int(or other conversions if t... |
8,571 | rapid introduction to procedural programming route "northprint(routetype(route)printsnorth here we create new object reference called route and set it to refer to new int of value at this point we could use with route since division is valid operation for integers then we reuse the route object reference to refer to ne... |
8,572 | "one"('one',when python outputs tuple it encloses it in parentheses many programmers emulate this and always enclose the tuple literals they write in parentheses if we have one-item tuple and want to use parentheseswe must still use the comma--for example( ,an empty tuple is created by using empty parentheses(the comma... |
8,573 | rapid introduction to procedural programming tupleslistsand strings are "sized"that isthey are data types that have notion of sizeand data items of any such data type can be meaningfully passed to the len(function (an exception is raised if nonsized data item is passed to len(all python data items are objects (also cal... |
8,574 | the dot ("access attribute"operator is used to access an object' attributes an attribute can be any kind of objectalthough so far we have shown only method attributes since an attribute can be an object that has attributeswhich in turn can have attributesand so onwe can use as many dot operators as necessary to access ... |
8,575 | rapid introduction to procedural programming the identity operator since all python variables are really object referencesit sometimes makes sense to ask whether two or more object references are referring to the same object the is operator is binary operator that returns true if its left-hand object reference is refer... |
8,576 | equal to>greater than or equal toand greater than these operators compare object valuesthat isthe objects that the object references used in the comparison refer to here are few examples typed into python shella = false true ba (truetruefalsefalseeverything is as we would expect with integers similarlystrings appear to... |
8,577 | rapid introduction to procedural programming difference if computing the data item' value is expensiveor if accessing the data item causes side effects thanks to the "strongaspect of python' dynamic typingcomparisons that don' make sense will cause an exception to be raised for example"three traceback (most recent call... |
8,578 | "hanin phrase true convenientlyin the case of stringsthe membership operator can be used to test for substrings of any length (as noted earliera character is just string of length logical operators python provides three logical operatorsandorand not both and and or use short-circuit logic and return the operand that de... |
8,579 | rapid introduction to procedural programming piece # control flow statements |we mentioned earlier that each statement encountered in py file is executed in turnstarting with the first one and progressing line by line the flow of control can be diverted by function or method call or by control structuresuch as conditio... |
8,580 | there can be zero or more elif clausesand the final else clause is optional if we want to account for particular casebut want to do nothing if it occurswe can use pass as that branch' suite the first thing that stands out to programmers used to +or java is that there are no parentheses and no braces the other thing to ... |
8,581 | rapid introduction to procedural programming while boolean_expressionsuite actuallythe while loop' full syntax is more sophisticated than thissince both break and continue are supportedand also an optional else clause that we will discuss in the break statement switches control to the statement following the innermost ... |
8,582 | in factan entire list (or tuplecan be printed using the print(function directlyfor exampleprint(countries)but we often prefer to print collections using for loop (or list comprehensioncovered later)to achieve full control over the formatting for letter in "abcdefghijklmnopqrstuvwxyz"if letter in "aeiou"print(letter"is ... |
8,583 | rapid introduction to procedural programming this occurs and if the as variable part is giventhen inside the exception-handling suitevariable refers to the exception object if an exception occurs in the handling except blockor if an exception is raised that does not match any of the except blocks in the first placepyth... |
8,584 | - notice that can be used both as unary operator (negationand as binary operator (subtraction)as is common in most programming languages where python differs from the crowd is when it comes to division the division operator produces floating-point valuenot an integermany other languages will produce an integertruncatin... |
8,585 | er handmutable types can be more convenient to use where the distinction matterswe will discuss it--for examplein when we discuss setting default arguments for custom functionsin when we discuss listssetsand some other data typesand again in when we show how to create custom data types the right-hand operand for the li... |
8,586 | rapid introduction to procedural programming ter in this subsection we will concentrate on console /oand use shell redirection for reading and writing files python provides the built-in input(function to accept input from the user this function takes an optional string argument (which it prints on the console)it then w... |
8,587 | exception handler that prints suitable message and switches control to the start of the loop ("continues the loop"and the last if statement ensures that if the user doesn' enter any numbers at allthe summary isn' outputand division by zero is avoided file handling is fully covered in but right now we can create files b... |
8,588 | rapid introduction to procedural programming given the command line sum py data\sum dat (where the sum dat file contains list of numbers one per line and is in the examplesdata subdirectory)the output to the console istype integerseach followed by enteror ^ or ^ to finish count total mean we have made several small cha... |
8,589 | lating suites as functions which can be parameterized by the arguments they are passed here is the general syntax for creating functiondef functionname(arguments)suite the arguments are optional and multiple arguments must be comma-separated every python function has return valuethis defaults to none unless we return f... |
8,590 | rapid introduction to procedural programming python module is just py file that contains python codesuch as custom function and class (custom data typedefinitionsand sometimes variables to access the functionality in module we must import it for exampleimport sys to import module we use the import statement followed by... |
8,591 | examples ||in the preceding section we learned enough python to write real programs in this section we will study two complete programs that use only the python covered earlier this is both to show what is possibleand to help consolidate what has been learned so far in subsequent we will increasingly cover more of pyth... |
8,592 | rapid introduction to procedural programming zero [**"""*""*""*""**"one detail to note is that the zero list of strings is spread over multiple lines python statements normally occupy single linebut they can span multiple lines if they are parenthesized expressiona listsetor dictionary literala function call argument l... |
8,593 | trydigits sys argv[ row while row line "column while column len(digits)number int(digits[column]digit digits[numberline +digit[rowcolumn + print(linerow + except indexerrorprint("usagebigdigits py "except valueerror as errprint(err"in"digitsthe whole code is wrapped in an exception handler that can catch the two things... |
8,594 | rapid introduction to procedural programming if the conversion succeedswe use number as an index into the digits listfrom which we extract the digit list of strings we then add the row-th string from this list to the line we are building upand also append two spaces to give some horizontal separation between each digit... |
8,595 | def get_int(msgminimumdefault)while truetryline input(msgif not line and default is not nonereturn default int(lineif minimumprint("must be >="minimumelsereturn except valueerror as errprint(errthis function requires three argumentsa message stringa minimum valueand default value if the user just presses enter there ar... |
8,596 | rapid introduction to procedural programming once we know how many rows and columns the user requires and the minimum and maximum values of the random numbers they wantwe are ready to do the processing row while row rowsline "column while column columnsi random randint(minimummaximums str(iwhile len( line + column + pr... |
8,597 | literals are written using single or double quotesit doesn' matter which as long as the same kind of quote is used at both ends we can convert between strings and integersfor exampleint(" "and str( if an integer conversion fails valueerror exception is raisedwhereas almost anything can be converted to string strings ar... |
8,598 | rapid introduction to procedural programming result--and this may not be boolean (although it can be converted to boolean)not always returns either true or false we can test for membership of sequence typesincluding stringslistsand tuplesusing the in and not in operators membership testing uses slow linear search on li... |
8,599 | examples exercises exercises ||the purpose of the exercises hereand throughout the bookis to encourage you to experiment with pythonand to get hands-on experience to help you absorb each material the examples and exercises cover both numeric and text processing to appeal to as wide an audience as possibleand they are k... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.