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 program in factyou probably don' write any code until you can build picture in your mind of what the code does and how the pieces of the code interact the more you can picture this "organic whole,the more likely you are to feel comfortable that you have developed the best solution to the problem if you don' grasp this whole right awayyou might keep staring out the window for timeeven though the basic solution to the problem is quite obvious in one senseyou feel that the most elegant solution will be more reusable and more maintainablebut even if you are the sole likely programmeryou feel reassured when you have designed solution that is relatively elegant and doesn' expose too many internal inelegancies one of the main reasons computer science researchers began to recognize design patterns is to satisfy this need for elegant but simple reusable solutions the term design patterns sounds bit formal to the uninitiated and can be somewhat off-putting when you first encounter it butin factdesign patterns are just convenient ways of reusing object-oriented code between projects and programmers the idea behind design patterns is simpleto write down and catalog common interactions between objects that programmers have frequently found useful one frequently cited pattern from early literature on programming frameworks is the modelview-controller framework for smalltalk (krasner and pope )which divided the user interface problem into three parts the parts were referred to as data modelcontaining the computational parts of the programthe viewwhich presents the user interfaceand the controllerwhich interacts between the user and the view (see figure - |
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 accomplished that very nicely three objects talking to each other using this restrained set of connections is an example of powerful design pattern in other wordsdesign patterns describe how objects communicate without become entangled in each other' data models and methods keeping this separation has always been an objective of good oo programming if you have been trying to keep objects minding their own businessyou are probably already using some of the common design patterns design patterns started to be recognized more formally in the early by erich gamma, who described patterns incorporated in the gui application framework et+the culmination of these discussions and number of technical meetings was the book design patternselements of reusable softwareby gammahelmjohnsonand vlissides this best-selling bookcommonly referred to as the gang of fouror "gofbookhas had powerful impact on programmers seeking to understand how to use design patterns it describes commonly occurring and generally useful patterns and comments on how and when you might apply them throughout the following we refer to this groundbreaking book as design patterns since the publication of the original design patternsmany other useful books have been published these include our popular java design patternsa tutorial and an analogous book on cdesign patterns rhodes maintains an interesting site describing how python can make use of design patternsas well defining design patterns we all talk about the way we do things in our everyday workhobbiesand home lifeand recognize repeating patterns all the timeqq sticky buns are like dinner rollsbut add brown sugar and nut filling to them qq her front garden is like minebut in mine use astilbe qq this end table is constructed like that onebut in this onethe doors replace drawers |
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 algorithms that describe convenient ways for classes to communicate it has become apparent that you don' just write design pattern off the top of your head in factmost such patterns are discovered rather than written the process of looking for these patterns is called pattern mining and is worthy of book of its own the design patterns selected for inclusion in the original design patterns book were patterns that had several known applications and were on middle level of generalitywhere they could easily cross application areas and encompass several objects the authors divided these patterns into three typescreationalstructuraland behavioral qq qq qq creational patterns create objects for you instead of having you instantiate objects directly this gives your program more flexibility in deciding which objects need to be created for given case structural patterns help you compose groups of objects into larger structuressuch as complex user interfaces or accounting data behavioral patterns help you define the communication between objects in your system and control the flow in complex program the learning process we have found that learning design patterns is multiple-step process acceptance recognition internalization firstyou accept the premise that design patterns are important in your work then you recognize that you need to read about design patterns in order to determine when you might use them finallyyou internalize the patterns in sufficient detail that you know which ones might help you solve given design problem for some lucky peopledesign patterns are obvious toolsand they grasp their essential utility just by reading summaries of the patterns for many of the rest of usthere is slow induction period after we've read about patternfollowed by the proverbial "aha!when we see how we can apply them in our work these help take you to that final stage of internalization by providing completeworking programs that you can try out for yourself |
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-oriented approaches the fundamental reason for using design patterns is to keep classes separated and prevent them from having to know too much about one another equally importantusing these patterns helps you avoid reinventing the wheel and enables you to describe your programming approach succinctly in terms other programmers can easily understand there are number of strategies that oo programmers use to achieve this separationamong them encapsulation and inheritance nearly all languages that have oo capabilities support inheritance class that inherits from parent class has access to all the methods of that parent class it also has access to all its variables howeverby starting your inheritance hierarchy with completeworking classyou might be unduly restricting yourself as well as carrying along specific method implementation baggage insteaddesign patterns suggests that you always program to an interface and not to an implementation putting this more succinctlyyou should define the top of any class hierarchy with an abstract class or an interfacewhich implements no methods but simply defines the methods that class will support then in all your derived classesyou have more freedom to implement these methods as best suits your purposes python does not directly support interfacesbut it does let you write abstract classeswhere the methods have no implementation remember the comd interface to the dbutton classclass dbutton(button)def __init__(selfmaster**kwargs)super(__init__(master**kwargssuper(config(command=self comdabstract method to be called by children def comd(self)pass this is good example of an abstract class here you fill in the code for the command method in the derived button classes as you will seeit is also an example of the command design pattern the other major concept you should recognize is object composition we have already seen this approach in the statelist examples object composition is simply the construction of objects that contain others--the encapsulation of several objects inside another one many beginning oo programmers tend to use inheritance to solve every problembut as you begin to write more elaborate programsthe merits of object composition become apparent your new object can have the interface that works best for what you want to accomplish without having all the methods of the parent classes thusthe second major precept suggested by design patterns is favor object composition over inheritance |
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 bookalong with at least one working program example for that pattern the programs have some sort of visual interface as well to make them more immediate to you which design patterns are most usefulthis depends on the individual programmer the ones we use the most are commandfactorydecoratorfacadeand mediatorbut we have used nearly every one at some point references erich gammaobject-oriented software development based on et++(in german(springerverlagberlin erich gammarichard helmralph johnsonand john vlissidesdesign patternselements of reusable object-oriented software (readingmaaddison-wesley james cooperjava design patternsa tutorial (bostonaddison-wesley james coopercdesign patternsa tutorial (bostonaddison-wesley brandon rhodes"python 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 adapter creating adapters - github programs moving data between lists - pluggable adapters two-way adapters adapters class adapter creating - pluggable adapters two-way adapters |
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 - lists range function interpreter pattern assignment (=operator attrgetter operatorsorting - attrgetter operatorsorting - consequences of - console interface - bar graphsline and bar graph strategies - behavioral patterns chain of responsibility pattern - github programs languages - parsing - print verb report generator example - consequences of - usefulness of - first cases user interfaces - github programs using help systemsprogramming - variable class help systemstree structures - verb class iterator pattern calling iterators listboxes - composites and iterators receiving help command - consequences of - requests creating iterators sample code - dunder methods using external iterators command pattern buttoncommand objects fibonacci iterators - - buttonscreating filtered iterators - buttonsundo button - generators in classes command objects getting iterators command objectsbuilding - github programs command objectscalling - internal iterators |
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 commands - github programs sample code - interactions between controls using - mediator pattern sample code - single interface mediators - memento pattern template pattern callbacks concrete methods caretaker class - consequences of consequences of empty methods github programs github programs graphics drawing program example - hook methods sample code - isoscelestriangle class using - point class observer pattern - isosceles triangles sample code - color changing program example - standard triangles consequences of summary of github programs template class messages to the media triangle class - notifications triangle drawing program state pattern stdtriangle class using consequences of visitor pattern github programs boss class - graphics drawing program example - bvacationvisitor class - sample code - statemanagermediator interactions - statemanagerswitching between states consequences of double dispatching github programs sample code - traversing series of classes |
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 - bvacationvisitor classvisitor pattern - byte codes break statements bridge pattern - consequences of - style formatting creating user interfaces caching resultscomposite pattern extending bridges - callbackstemplate pattern github programs calling listbox builder - buildersbuilder pattern - treeview widget - command objects - bridgesextending - functions builder pattern - iterators calling builders - camelcase checkbox builder caretaker classmemento pattern - consequences of github programs investment trackers - listbox builder - selected securitiesdisplaying thought questions case (upper/lowercamelcase classes constants functions - variables buttoncommand objectscommand pattern catching errors - buttons chain of responsibility pattern - blue buttoncreating consequences of - checkbuttonsgrid layouts - first cases creating github programs command pattern help commandreceiving - object-oriented programming - help systems visual programming - programming - tree structures - |
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 classcommand pattern naming conventions plotstategy classstrategy pattern - blank lines point classtemplate pattern boss class query classfacade pattern - composite pattern results classfacade pattern visitor pattern - static classessingleton pattern bvacationvisitor classvisitor pattern - camelcase caretaker classmemento pattern - collections communicating between stdtriangle classtemplate pattern subclassesfactory pattern - table classfacade pattern template classmethods traversing series of classesvisitor pattern context classstrategy pattern triangle classtemplate pattern - creating variable classinterpreter pattern database classfacade pattern - variables - decorator class - verb classinterpreter pattern derived classes visiting docstrings visitor class - employee classcomposite pattern - facade classesbuilding - factory classesoperation of - factory method pattern circleseeding class - event classes - straight seeding class - swimmer class - cloning - codingimpenetrable collections classes dictionaries combining listing using - |
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 using spacing color color changing program exampleobserver pattern - tkinter libraryapplying color with combining arithmetic/assignment statements common mistakespython decision making communicating between classes comparison operators - compilingsimple python program example conditions complement operator - dictionaries complete python programswriting combo boxes - complex numbers command pattern composite pattern buttoncommand objects boss class buttons caching results creating undo button - command objects building - calling - containers mediators and - composite implementation consequences of doubly linked lists - employee class - employee trees building printing - consequences of github programs github programs iterators keyboard example - leaf nodes - keymoderator class recursive calls stet references salary computation undo function - simple composites treeviews of composites - |
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 github programs straight seeding class - using factory pattern naming conventions building numeric constants factory classes - containers github programs command objects gui iterable containers math computations context classstrategy pattern sample code continue statements subclasses - controlsinteractions between thought questions copyinglists copy-on write objects using - prototype pattern flyweight pattern cloning - proxy pattern consequences of cpython github programs creational patterns using - abstract factory pattern singleton pattern - consequences of - consequences of gardenmaker factory - github programs github programs large programs - purposes of - static classes thought questions throwing exceptions user interfaces summary of builder pattern - calling builders - checkbox builder data modificationiterators consequences of data tables - displaying selected securities combo boxes - github programs listboxescreating - investment trackers - state datadisplaying - |
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 decorators - datesformatting def keywordfunctions dbobjectsfacade pattern derived classes decision making in python design patterns see also separate entries arraysrange function assignment (=operator defined - break statements learning process - combining conditions model-view-controller framework for smalltalk - common mistakes continue statements elif (else ifstatements - format string function formatting dates formattingc style formattingjava style -string formatting numbers strings object-oriented strategies objects over inheritance popularity of programming to interfaces resources development environments anaconda command-line execution cpython google colaboratory github programs idle if statements ipython else clauses range function jupyter notebook jython is equal to (==operator liclipse - line length pycharm lists thonny - looping statements visual studio for loops wing match function - dictionaries pattern matching - combining print function - listing declaring variables using - |
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 linked listscomposite pattern - executable python programscreating - downloading sqlite extending bridges - drawing external iterators drawing program example memento pattern - state pattern - facade pattern - isosceles triangles classesbuilding - rectangles/squares - consequences of standard triangles database class - triangle drawing program database objects dunder methods databasescreating - dbobjects github programs elif (else ifstatements - mysql databaseconnections else clausesif statements mysql workbench employee classcomposite pattern - results class employee trees query class - sqlite building table class printing - tables empty methods equal signs (=creating - names - assignment (=operator factory classesoperation of - initialization factory method pattern - is equal to (==operator circleseeding class - spacing event classes - |
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 keyword sample code docstrings subclasses - format string function thought questions github programs using - len functionstrings fibonacci iterators - - map function - file dialogs - masking function see and operator files match function - opening naming conventions - reading - print function - filtered iterators - range functionarrays first caseschain of responsibility pattern returning tuples flyweight pattern undo functioncommand pattern - copy-on write objects starting python programs - example code - flyweightsdefined folders as flyweights - selecting - github programs folders gardenmaker factory - github programs abstract factory pattern account setup adapter pattern as flyweights - bridge pattern selectingflyweight pattern - builder pattern for loops - chain of responsibility pattern for statements collections format string function command pattern formatting composite pattern style formatting decorator pattern -string formatting facade pattern |
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 singleton pattern state pattern strategy pattern template pattern visitor pattern visual programming data tables - examples google colaboratory graphics drawing program example memento pattern - state pattern - grid layouts - gui (graphical user interfaces)factory pattern hello buttonscreating help commandreceiving - help systems programming - tree structures - hintstype hook methods else clauses range function images displaying with pil loading with threads - pil displaying images using - impenetrable coding importing names to tkinter library tkinter library tools indentation comments loops/classes statements indexesnegative inheritance multiple inheritance - objects over inheritance initializationequal signs (=) input statements input (user)responding to - inserting tree nodes in data tables - installing mysql python instances classessingleton pattern - creating integer division interactions between controlsmediator pattern |
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 programs java style formatting languages - jpg filespil parsing - print verb displaying images using - report generator example - jupyter notebook usefulness of - jython user interfaces - using variable class verb class investment trackers - keyboardscommand pattern - keymoderator classcommand pattern ipython is equal to (==operator isosceles trianglesdrawing isoscelestriangle classtemplate pattern iterable containers iterator pattern calling iterators composites and iterators consequences of - creating iterators labelframe widget - languagesinterpreter pattern - large programssingleton pattern - layouts grid layouts - pack layouts - - leaf nodescomposite pattern - learning design patterns - dunder methods left/right shift operators external iterators len functionstrings fibonacci iterators - - liclipse - filtered iterators - line and bar graph strategies - generators in classes line length in python getting iterators listbox builder github programs bridge pattern - builder pattern - |
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 - strings github programs moving data between - if statements slicing else clauses spacing range function loading images with threads - is equal to (==operator local variables line length logging from threads lists looping statements looping statements loops for loops break statements match function - continue statements pattern matching - indentation print function - for loops - map function - with loops - masking function see and operator for loopsas iteratorsmatch function - lower/upper case matching patterns - camelcase math computationsfactory pattern classes mediator pattern constants command objects - functions - consequences of variables example system - making decisions in python arraysrange function assignment (=operator github programs interactions between controls sample code - single interface mediators - memento pattern break statements caretaker class - combining conditions consequences of common mistakes github programs |
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 boxes comma-separated numbers messages to the mediaobserver pattern methods accessor methods concrete methods complex numbers datesformatting formatting numeric constants dunder methods empty methods hook methods revised methodsclass creation strings - template methods mistakes (common)python decision making model-view-controller framework for smalltalk - object-oriented programming buttonscreating - classes - collections creating derived classes inheritance modifying dataiterators inheritancemultiple inheritance - movingdata between lists - instances multiple inheritance - variables - defined mysql database connections inheritance installing methods pycharm polymorphism pymysql library rectangles/squaresdrawing - mysql workbench named constants see variables naming conventions classes constants types declaring - hints variables local variables properties visibility |
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 polymorphism proxy pattern prefix/suffix removalstrings database objectsfacade pattern print function - over inheritance print verbinterpreter pattern observer pattern - printing employee trees - color changing program example - privileged accessiterators - consequences of program commandsstrategy pattern - github programs programminghelp systems - messages to the media properties notifications prototype pattern odbc (open database connectivity) cloning - openingfiles consequences of or operator github programs operators using - and operator proxy pattern arithmetic operators comparing related patterns - assignment (=operator copy-on write objects bitwise operators - github programs comparison operators - pil complement operator - displaying images compound operatorsspacing using - is equal to (==operator left/right shift operators or operator threads loading images - logging from in strings pycharm pymysql library python pack layouts - - arrayslists parsinginterpreter pattern - classes |
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 execution complex numbers cpython constants google colaboratory character constants - idle named constants see variables ipython naming conventions jupyter notebook numeric constants jython data types liclipse - decision making pycharm assignment (=operator thonny - break statements visual studio combining conditions common mistakes wing dictionaries continue statements listing elif (else ifstatements - using - format string function formattingc style formattingdates equal signs (=initialization with spacing formattingf-string executable programscreating - formattingjava style formattingdates formattingnumbers -string formatting formattingstrings functions github programs blank lines if statements calling if statementselse clauses def keyword if statementsrange function docstrings is equal to (==operator format string function line length github programs lists map function - |
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 - github programs iconscreating - if statements installing if statementselse clauses integer division if statementsrange function line length indentation lists input statements changing contents - looping statements comprehension for statements copying strings slicing formatting spacing len function loops methods - break statements in operators continue statements prefix/suffix removal for loops representing - indentation slicing with loops - negative indexes operators - tuplesusing variables boolean variables and operator declaring arithmetic operators naming conventions - bitwise operators - comparison operators - compound operators left/right shift operators or operator reassigning values upper/lower case pattern matching - query classfacade pattern - pep standards queuing commands running programs quit buttonscreating - setsusing |
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 pattern - requestschain of responsibility pattern responding to user input - responsibility patternchain of - consequences of - selected securitiesdisplaying selecting foldersflyweight pattern - series of classestraversing setsusing shortcutscreating - simple composites simple factory pattern building factory classesoperation of - github programs gui math computations sample code subclasses - thought questions using - single interface mediators - singleton pattern - first cases consequences of github programs exceptionsthrowing help commandreceiving - github programs help systems large programs - programming - tree structures - listboxes - static classes slicing lists strings requests sample code - using smalltalkmodel-view-controller framework - results classfacade pattern sortingattrgetter operator - returning tuples spacing revised methodsclass creation salary computationcomposite pattern securities (selected)displaying seeding programfactory method pattern - arithmetic operators comments equal signs (=) lists sqlite downloading facade pattern |
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 code - formatting statemanager -string formatting format string function mediator interactions - len function switching between states methods - switching between states prefix/suffix removal transitions representing - statemanager mediator interactions - switching between states statements slicing structural patterns - adapter pattern class adapter break statements creating adapters - combined arithmetic/assignment statements github programs continue statements elif (else ifstatements - for statements if statements else clauses range function indentation input statements looping statements switch statements see match function static classessingleton pattern moving data between lists - pluggable adapters two-way adapters bridge pattern - consequences of - creating user interfaces extending bridges - github programs listbox builder - treeview widget - composite pattern stdtriangle classtemplate pattern boss class straight seeding classfactory method pattern - building employee trees strategy pattern composite implementation consequences of - context class caching results consequences of |
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 programs simple composites pildisplaying images treeviews of composites - pilusing - decorator pattern buttons - consequences of - threadsloading images - threadslogging from summary of dataclass decorator - subclassesfactory pattern - decorated code - suffix/prefix removal decorator class - github programs swimmer classfactory method pattern - nonvisual decorators - switch statements see match function facade pattern - building classes - consequences of switching between states syntaxpython classes creating databases - blank lines creating tables - docstrings database class - indentation database objects naming conventions dbobjects github programs mysql database connections comments docstrings spacing mysql workbench complex numbers query class - constants results class character constants - sqlite named constants see variables table class naming conventions tables names - flyweight pattern copy-on write objects example code - numeric constants data types equal signs (=initialization with spacing |
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 operators treeview widget - bitwise operators - namesfacade pattern - comparison operators - template classmethods complement operator - template methods compound operators left/right shift operators or operator pep standards pythonindentation statements combined arithmetic/assignment statements indentation input statements strings len function methods - in operators representing - slicing variables boolean variables declaring naming conventions - template pattern callbacks concrete methods consequences of empty methods github programs hook methods isosceles triangles isoscelestriangle class point class sample code - standard triangles stdtriangle class summary of template class triangle class - triangle drawing program using thonny - thought questions reassigning values abstract factory pattern upper/lower case builder pattern factory pattern |
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 python basic syntax first python program python identifiers python keywords lines and indentation multi-line statements |
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 multiple assignment standard data types python numbers python strings python lists python tuples python dictionary data type conversion python basic operators types of operators python arithmetic operators python comparison operators |
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 suites for loop iterating by sequence index using else statement with loops nested loops loop control statements break statement continue statement pass 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(widthfillcharmethod count(strbeg ,end=len(string)method decode(encoding='utf- ',errors='strict'method encode(encoding='utf- ',errors='strict'method endswith(suffixbeg= end=len(string)method expandtabs(tabsize= find(strbeg= end=len(string) index(strbeg= end=len(string) isalnum(method isalpha( |
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('\ ') startswith(strbeg= ,end=len(string) strip([chars] swapcase( title( translate(tabledeletechars="" |
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,obj list pop(obj=list[- ] list remove(obj list reverse( list sort([func] |
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 properties of dictionary keys built-in dictionary functions and methods cmp(dict dict len(dict str(dict type( dict clear( dict copy( |
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 ctime([secs] time gmtime([secs] time localtime([secs] time mktime(tupletime time sleep(secs time strftime(fmt[,tupletime] time strptime(str,fmt='% % % % :% :% % ' |
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 global vs local variables python modules the import statement the from import statement the from import statement locating modules the pythonpath variable namespaces and scoping the dirfunction |
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 deleting files the rename(method the remove(method directories in python the mkdir(method the chdir(method the getcwd(method the rmdir(method file and directory related methods |
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 exception the except clause with no exceptions the except clause with multiple exceptions the try-finally clause argument of an exception raising an exception user-defined exceptions |
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 matching versus searching search and replace regular-expression modifiersoption flags regular-expression patterns regular-expression examples grouping with parentheses backreferences python cgi programming what is cgi web browsing |
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 program passing text area data to cgi program passing drop down box data to cgi program using cookies in cgi how it works setting up cookies retrieving cookies file upload example how to raise "file downloaddialog box python database access what is mysqldb how do install mysqldb database connection creating database table |
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 modules further readings python sending email sending an html -mail using python sending attachments as an -mail python multithreading starting new thread the threading module |
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 entry frame label listbox menubutton menu message radiobutton |
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 first look at python extension the header file python the functions |
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 the interpreter you do not need to compile your program before executing it this is similar to perl and php python is interactiveyou can actually sit at python prompt and interact with the interpreter directly to write your programs python is object-orientedpython supports object-oriented style or technique of programming that encapsulates code within objects python is beginner' languagepython is great language for the beginner-level programmers and supports the development of wide range of applications from simple text processing to www browsers to games history of python python was developed by guido van rossum in the late eighties and early nineties at the national research institute for mathematics and computer science in the netherlands python is derived from many other languagesincluding abcmodula- cc++algol- smalltalkunix shelland other scripting languages python is copyrighted like perlpython source code is now available under the gnu general public license (gplpython is now maintained by core development team at the institutealthough guido van rossum still holds vital role in directing its progress python features python' features includeeasy-to-learnpython has few keywordssimple structureand clearly defined syntax this allows the student to pick up the language quickly easy-to-readpython code is more clearly defined and visible to the eyes easy-to-maintainpython' source code is fairly easy-to-maintain broad standard librarypython' bulk of the library is very portable and crossplatform compatible on unixwindowsand macintosh interactive modepython has support for an interactive mode which allows interactive testing and debugging of snippets of code |
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 databases gui programmingpython supports gui applications that can be created and ported to many system callslibrariesand windows systemssuch as windows mfcmacintoshand the window system of unix scalablepython provides better structure and support for large programs than shell scripting apart from the above-mentioned featurespython has big list of good featuresfew are listed belowit supports functional and structured programming methods as well as oop it can be used as scripting language or can be compiled to byte-code for building large applications it provides very high-level dynamic data types and supports dynamic type checking it supports automatic garbage collection it can be easily integrated with cc++comactivexcorbaand java |
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/ macintosh (intelppc kos/ dos (multiple versionspalmos nokia mobile phones windows ce acorn/risc os beos amiga vms/openvms qnx vxworks psion python has also been ported to the java and net virtual machines getting python the most up-to-date and current source codebinariesdocumentationnewsetc is available on the official website of pythonyou can download python documentation from www python org/docthe documentation is available in htmlpdfand postscript formats installing python python distribution is available for wide variety of platforms you need to download only the binary code applicable for your platform and install python |
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 go to follow the link to download zipped source code available for unix/linux download and extract files editing the modules/setup file if you want to customize some options run /configure script make make install this installs python at standard location /usr/local/bin and /usr/local/lib/pythonxx where xx is the version of python its libraries at windows installation here are the steps to install python on windows machine open web browser and go to follow the link for the windows installer python-xyz msi file where xyz is the version you need to install to use this installer python-xyz msithe windows system must support microsoft installer save the installer file to your local machine and then run it to find out if your machine supports msi run the downloaded file this brings up the python install wizardwhich is really easy to use just accept the default settingswait until the install is finishedand you are done macintosh installation recent macs come with python installedbut it may be several years out of date see with extra tools to support development on the mac for older mac os' before mac os (released in )macpython is available jack jansen maintains it and you can have full access to the entire documentation at his website mac os installation |
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 command shell and other programs the path variable is named as path in unix or path in windows (unix is case-sensitivewindows is notin mac osthe installer handles the path details to invoke the python interpreter from any particular directoryyou must add the python directory to your path setting path at unix/linux to add the python directory to the path for particular session in unixin the csh shelltype setenv path "$path:/usr/local/bin/pythonand press enter in the bash shell (linux)type export ath="$path:/usr/local/bin/pythonand press enter in the sh or ksh shelltype path="$path:/usr/local/bin/pythonand press enter note/usr/local/bin/python is the path of the python directory setting path at windows to add the python directory to the path for particular session in windowsat the command prompttype path %path%; :\python and press enter notec:\python is the path of the python directory python environment variables here are important environment variableswhich can be recognized by pythonvariable pythonpath description it has role similar to path this variable tells the python interpreter where to locate the module files imported into program it should include the python source library directory and the directories |
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 to find the first caseinsensitive match in an import statement set this variable to any value to activate it pythonhome it is an alternative module search path it is usually embedded in the pythonstartup or pythonpath directories to make switching module libraries easy running python there are three different ways to start python( interactive interpreter you can start python from unixdosor any other system that provides you command-line interpreter or shell window enter python the command line start coding right away in the interactive interpreter $python unix/linux or pythonunix/linux or :>python windows/dos here is the list of all the available command line options |
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 python script sent in as cmd string run python script from given file ( script from the command-line python script can be executed at command line by invoking the interpreter on your applicationas in the following$python script py pythonscript py windows/dos unix/linuxor unix/linuxor :>python script py notebe sure the file permission mode allows execution ( integrated development environment you can run python from graphical user interface (guienvironment as wellif you have gui application on your system that supports python unixidle is the very first unix ide for python windowspythonwin is the first windows interface for python and is an ide with gui macintoshthe macintosh version of python along with the idle ide is available from the main websitedownloadable as either macbinary or binhex' files |
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 persistence filedirectoryand process handling networking and internet programming xml other modules summary exercise object-oriented programming the object-oriented approach object-oriented concepts and terminology custom classes attributes and methods inheritance and polymorphism using properties to control attribute access creating complete fully integrated data types custom collection classes creating classes that aggregate collections creating collection classes using aggregation creating collection classes using inheritance summary exercises xi |
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 (simple api for xmlrandom access binary files generic binaryrecordfile class examplethe bikestock module' classes summary exercises advanced programming techniques further procedural programming branching using dictionaries generator expressions and functions dynamic code execution and dynamic imports local and recursive functions function and method decorators function annotations further object-oriented programming controlling attribute access functors context managers descriptors class decorators abstract base classes multiple inheritance metaclasses functional-style programming partial function application xii |
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 find duplicate files program summary exercises networking creating tcp client creating tcp server summary exercises database programming dbm databases sql databases summary exercise regular expressions python' regular expression language characters and character classes quantifiers grouping and capturing assertions and flags the regular expression module xiii |
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 blocks domain-specific language parsing first-order logic lex/yacc-style parsing with ply simple key-value data parsing playlist data parsing parsing the blocks domain-specific language parsing first-order logic summary exercise introduction to gui programming dialog-style programs main-window-style programs creating main window creating custom dialog summary exercises epilogue selected bibliography index xiv |
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 methods common iterable operators and functions comparison special methods fundamental special methods numeric and bitwise special methods collection special methods bytes and bytearray methods # bytes and bytearray methods # bytes and bytearray methods # file object attributes and methods # file object attributes and methods # dynamic programming and introspection functions attribute access special methods the numbers module' abstract base classes the collections module' main abstract base classes db-api connection object methods db-api cursor object attributes and methods character class shorthands xv |
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 application written insayc+or java python is cross-platform languagein generalthe same python program can be run on windows and unix-like systems such as linuxbsdand mac os xsimply by copying the file or files that make up the program to the target machinewith no "buildingor compiling necessary it is possible to create python programs that use platform-specific functionalitybut this is rarely necessary since almost all of python' standard library and most third-party libraries are fully and transparently cross-platform one of python' great strengths is that it comes with very complete standard library--this allows us to do such things as download file from the internetunpack compressed archive fileor create web serverall with just one or few lines of code and in addition to the standard librarythousands of thirdparty libraries are availablesome providing more powerful and sophisticated facilities than the standard library--for examplethe twisted networking library and the numpy numeric library--while others provide functionality that is too specialized to be included in the standard library--for examplethe simpy simulation package most of the third-party libraries are available from the python package indexpypi python org/pypi python can be used to program in proceduralobject-orientedand to lesser extentin functional stylealthough at heart python is an object-oriented language this book shows how to write both procedural and object-oriented programsand also teaches python' functional programming features the purpose of this book is to show you how to write python programs in good idiomatic python styleand to be useful reference for the python language after the initial reading although python is an evolutionary rather than revolutionary advance on python some older practices are no longer appropriate or necessary in python and new practices have been introduced to take advantage of python features python is better language than python --it builds on the many years of experience with python and adds lots of new features (and omits python ' misfeatures)to make it even more of pleasure to use than python as well as more convenienteasierand more consistent |
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 be able to create library modules of your own the book is designed to be useful to several different audiencesincluding selftaught and hobbyist programmersstudentsscientistsengineersand others who need to program as part of their workand of coursecomputing professionals and computer scientists to be of use to such wide range of people without boring the knowledgeable or losing the less-experiencedthe book assumes at least some programming experience (in any languagein particularit assumes basic knowledge of data types (such as numbers and strings)collection data types (such as sets and lists)control structures (such as if and while statements)and functions in additionsome examples and exercises assume basic knowledge of html markupand some of the more specialized at the end assume basic knowledge of their subject areafor examplethe databases assumes basic knowledge of sql the book is structured in such way as to make you as productive as possible as quickly as possible by the end of the first you will be able to write small but useful python programs each successive introduces new topicsand often both broadens and deepens the coverage of topics introduced in earlier this means that if you read the in sequenceyou can stop at any point and you'll be able to write complete programs with what you have learned up to that pointand thenof courseresume reading to learn more advanced and sophisticated techniques when you are ready for this reasonsome topics are introduced in one and then are explored further in one or more later two key problems arise when teaching new programming language the first is that sometimes when it is necessary to teach one particular conceptthat concept depends on another conceptwhich in turn depends either directly or indirectly on the first the second is thatat the beginningthe reader may know little or nothing of the languageso it is very difficult to present interesting or useful examples and exercises in this bookwe seek to solve both of these problemsfirst by assuming some prior programming experienceand second by presenting python' "beautiful heartin --eight key pieces of python that are sufficient on their own to write decent programs one consequence of this approach is that in the early some of the examples are bit artificial in stylesince they use only what has been taught up to the point where they are presentedthis effect diminishes by until by the end of all the examples are written in completely natural and idiomatic python style the book' approach is wholly practicaland you are encouraged to try out the examples and exercises for yourself to get hands-on experience wherever |
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 python compatibility the "eg examples work with python or later--use these if you don' need to support python because your programsusers have python or later all of the examples have been tested on windowslinuxand mac os while it is best to use the most recent version of python this is not always possible if your users cannot or will not upgrade every example in this book works with python except where statedand those examples and features that are specific to python are clearly indicated as such although it is possible to use this book to develop software that uses only python for those wanting to produce software that is expected to be in use for many years and that is expected to be compatible with later python releasesit is best to use python as the oldest python version that you support this is partly because python has some very nice new featuresbut mostly because the python developers strongly recommend using python (or laterthe developers have decided that python will be the last python releaseand that there will be no more python releases even if bugs or security problems are discovered insteadthey want all python users to migrate to python (or to later version)which will have the usual bugfix and security maintenance releases that python versions normally have the structure of the book presents eight key pieces of python that are sufficient for writing complete programs it also describes some of the python programming environments that are available and presents two tiny example programsboth built using the eight key pieces of python covered earlier in the through introduce python' procedural programming featuresincluding its basic data types and collection data typesand many useful builtin functions and control structuresas well as very simple text file handling shows how to create custom modules and packages and provides an overview of python' standard library so that you will have good idea of the functionality that python provides out of the box and can avoid reinventing the wheel provides thorough introduction to object-oriented programming with python all of the material on procedural programming that you learned in earlier is still applicablesince object-oriented programming is |
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 this also shows how to write and read xml filesincluding using element treesdom (document object model)and sax (simple api for xml revisits material covered in some earlier exploring many of python' more advanced features in the areas of data types and collection data typescontrol structuresfunctionsand object-oriented programming this also introduces many new functionsclassesand advanced techniquesincluding functional-style programming and the use of coroutines--the material it covers is both challenging and rewarding is different from all the other in that it discusses techniques and libraries for debuggingtestingand profiling programsrather than introducing new python features the remaining cover various advanced topics shows techniques for spreading program' workload over multiple processes and over multiple threads shows how to write client/server applications using python' standard networking support covers database programming (both simple key-value "dbmfiles and sql databases explains and illustrates python' regular expression mini-language and covers the regular expressions module follows on from the regular expressions by showing basic parsing techniques using regular expressionsand also using two third-party modulespyparsing and ply finally introduces gui (graphical user interfaceprogramming using the tkinter module that is part of python' standard library in additionthe book has very brief epiloguea selected bibliographyand of coursean index most of the book' are quite long to keep all the related material together in one place for ease of reference howeverthe are broken down into sectionssubsectionsand sometimes subsubsectionsso it is easy to read at pace that suits youfor exampleby reading one section or subsection at time obtaining and installing python if you have modern and up-to-date mac or other unix-like system you may already have python installed you can check by typing python - (note the capital vin console (terminal app on mac os )--if the version is you've already got python and don' have to install it yourself if python wasn' found at all it may be that it has name which includes version number try |
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 python installedread on for windows and mac os xeasy-to-use graphical installer packages are provided that take you step-by-step through the installation process these are available from www python org/download for windowsdownload the "windows msi installer"unless you know for sure that your machine has different processor for which separate installer is supplied--for exampleif you have an amd get the "windows amd msi installeronce you've got the installerjust run it and follow the on-screen instructions for linuxbsdand other unixes (apart from mac os for which dmg installation file is provided)the easiest way to install python is to use your operating system' package management system in most cases python is provided in several separate packages for examplein ubuntu (from version )there is python for pythonidle-python for idle ( simple development environment)and python -doc for the documentation--as well as many other packages that provide add-ons for even more functionality than that provided by the standard library (naturallythe package names will start with python for the python versionsand so on if no python packages are available for your operating system you will need to download the source from www python org/download and build python from scratch get either of the source tarballs and unpack it using tar xvfz python- tgz if you got the gzipped tarball or tar xvfj python- tar bz if you got the bzip tarball (the version numbers may be differentfor examplepythontgz or pythontar bz in which case simply replace with your actual version number throughout the configuration and building are standard firstchange into the newly created python- directory and run /configure (you can use the --prefix option if you want to do local install nextrun make it is possible that you may get some messages at the end saying that not all modules could be built this normally means that you don' have some of the required libraries or headers on your machine for exampleif the readline module could not be builtuse the package management system to install the corresponding development libraryfor examplereadline-devel on fedorabased systems and readline-dev on debian-based systems such as ubuntu another module that may not build straight away is the tkinter module--this depends on both the tcl and tk development librariestcl-devel and tk-devel on fedora-based systemsand tcl -dev and tk -dev on debian-based systems (and where the minor version may not be unfortunatelythe relevant package names are not always so obviousso you might need to ask for help on |
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 for python if you installed intosay~/local/python then by adding the ~/local/python /bin directory to your pathyou will be able to run python using python and idle using idle alternativelyif you already have local directory for executables that is already in your path (such as ~/bin)you might prefer to add soft links instead of changing the path for exampleif you keep executables in ~/bin and you installed python in ~/local/python you could create suitable links by executing ln - ~/local/python /bin/python ~/bin/python and ~/local/python /bin/idle ~/bin/idle for this book we did local install and added soft links on linux and mac os exactly as described here--and on windows we used the binary installer if you did not use --prefix and have root accesslog in as root and do make install on sudo-based systems like ubuntudo sudo make install if python is on the system/usr/bin/python won' be changedand python will be available as python (or python depending on the version installedand from python in additionas python python ' idle is installed as idleso if access to python ' idle is still required the old idle will need to be renamed--for exampleto /usr/bin/idle --before doing the install python installs idle as idle and so does not conflict with python ' idle acknowledgments would first like to acknowledge with thanks the feedback have received from readers of the first editionwho gave correctionsor made suggestionsor both my next acknowledgments are of the book' technical reviewersstarting with jasmin blanchettea computer scientistprogrammerand writer with whom have cowritten two ++/qt books jasmin' involvement with planning and his suggestions and criticisms regarding all the examplesas well as his careful readinghave immensely improved the quality of this book georg brandl is leading python developer and documentor responsible for creating python' new documentation tool chain georg spotted many subtle mistakes and very patiently and persistently explained them until they were understood and corrected he also made many improvements to the examples |
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 previous booksand has once again come to my aid trenton' careful reading and the numerous suggestions that he made helped clarify many issues and have led to considerable improvements to the text in addition to the aforementioned reviewersall of whom read the whole bookdavid boddiea senior technical writer at nokia' qt software and an experienced python practitioner and open source developerhas read and given valuable feedback on portions of it for this second editioni would also like to thank paul mcguire (author of the pyparsing module)who was kind enough to review the pyparsing examples that appear in the new on parsingand who gave me lot of thoughtful and useful advice and for the same david beazley (author of the ply modulereviewed the ply examples and provided valuable feedback in additionjasmintrentongeorgand phil read most of this second edition' new materialand provided very valuable feedback thanks are also due to guido van rossumcreator of pythonas well as to the wider python community who have contributed so much to make pythonand especially its librariesso useful and enjoyable to use as alwaysthanks to jeff kingstoncreator of the lout typesetting language that have used for more than decade special thanks to my editordebra williams cauleyfor her supportand for once again making the entire process as smooth as possible thanks also to anna popickwho managed the production process so welland to the proofreaderaudrey doylewho did such fine work once again and for this second edition also want to thank jennifer lindner for helping me keep the new material understandableand the first edition' japanese translator takahiro nafor spotting some subtle mistakes which 've been able to correct gao in this edition last but not leasti want to thank my wifeandreaboth for putting up with the wake-ups when book ideas and code corrections often arrived and insisted upon being noted or tested there and thenand for her loveloyaltyand support |
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 you learn here (the introduction explains how to obtain and install python on all major platforms this first section shows you how to create and execute python programs you can use your favorite plain text editor to write your python codebut the idle programming environment discussed in this section provides not only code editorbut also additional functionalityincluding facilities for experimenting with python codeand for debugging python programs the second section presents eight key pieces of python that on their own are sufficient to write useful programs these pieces are all covered fully in later and as the book progresses they are supplemented by all of the rest of python so that by the end of the bookyou will have covered the whole language and will be able to use all that it offers in your programs the final section introduces two short programs which use the subset of python features introduced in the second section so that you can get an immediate taste of python programming creating and running python programs ||python code can be written using any plain text editor that can load and save text using either the ascii or the utf- unicode character encoding by defaultpython files are assumed to use the utf- character encodinga superset of ascii that can represent pretty well every character in every language python files normally have an extension of pyalthough on some unix-like sys character encodings |
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 modulesand pyw for gui programs all the examples presented in this book run unchanged on all platforms that have python available just to make sure that everything is set up correctlyand to show the classical first examplecreate file called hello py in plain text editor (windows notepad is fine--we'll use better editor shortly)with the following contents#!/usr/bin/env python print("hello""world!"the first line is comment in pythoncomments begin with and continue to the end of the line (we will explain the rather cryptic comment in moment the second line is blank--outside quoted stringspython ignores blank linesbut they are often useful to humans to break up large blocks of code to make them easier to read the third line is python code herethe print(function is called with two argumentseach of type str (stringi sequence of characterseach statement encountered in py file is executed in turnstarting with the first one and progressing line by line this is different from some other languagesfor examplec+and javawhich have particular function or method with special name where they start from the flow of control can of course be diverted as we will see when we discuss python' control structures in the next section we will assume that windows users keep their python code in the :\py eg directory and that unix ( unixlinuxand mac os xusers keep their code in the $home/py eg directory save hello py into the py eg directory and close the text editor now that we have programwe can run it python programs are executed by the python interpreterand normally this is done inside console window on windows the console is called "console"or "dos prompt"or "ms-dos prompt"or something similarand is usually available from start-all programs-accessories on mac os the console is provided by the terminal app program (located in applications/utilities by default)available using finderand on other unixeswe can use an xterm or the console provided by the windowing environmentfor examplekonsole or gnome-terminal start up consoleand on windows enter the following commands (which assume that python is installed in the default location)--the console' output is shown in lightfacewhat you type is shown in bold |
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 that unless stated otherwisepython' behavior on mac os is the same as that on any other unix system in factwhenever we refer to "unixit can be taken to mean linuxbsdmac os xand most other unixes and unix-like systems although the program has just one executable statementby running it we can infer some information about the print(function for one thingprint(is built-in part of the python language--we didn' need to "importor "includeit from library to make use of it alsoit separates each item it prints with single spaceand prints newline after the last item is printed these are default behaviors that can be changedas we will see later another thing worth noting about print(is that it can take as many or as few arguments as we care to give it typing such command lines to invoke our python programs would quickly become tedious fortunatelyon both windows and unix we can use more convenient approaches assuming we are in the py eg directoryon windows we can simply typec:\py eg\>hello py windows uses its registry of file associations to automatically call the python interpreter when filename with extension py is entered in console unfortunatelythis convenience does not always worksince some versions of windows have bug that sometimes affects the execution of interpreted programs that are invoked as the result of file association this isn' specific to pythonother interpreters and even some bat files are affected by the bug too if this problem arisessimply invoke python directly rather than relying on the file association if the output on windows isthe unix prompt may well be different from the shown hereit does not matter what it is print( |
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 (assuming it is installed in the default location)and execute it explicitly each time (this also gets around the windows file association bug mentioned earlier for examplec:\py eg\>path= :\python ;%pathc:\py eg\>python hello py it might be more convenient to create py bat file with the single line path= :\python ;%pathand to save this file in the :\windows directory thenwhenever you start console for running python programsbegin by executing py bat or alternatively you can have py bat executed automatically to do thischange the console' properties (find the console in the start menuthen right-click it to pop up its properties dialog)and in the shortcut tab' target stringappend the text / / :\windows\py bat(note the space beforebetweenand after the "/uand "/koptionsand be sure to add this at the end after "cmd exe"on unixwe must first make the file executableand then we can run itchmod + hello py /hello py we need to run the chmod command only once of courseafter that we can simply enter /hello py and the program will run on unixwhen program is invoked in the consolethe file' first two bytes are read if these bytes are the ascii characters #!the shell assumes that the file is to be executed by an interpreter and that the file' first line specifies which interpreter to use this line is called the shebang (shell executelineand if present must be the first line in the file the shebang line is commonly written in one of two formseither#!/usr/bin/python or#!/usr/bin/env python if written using the first formthe specified interpreter is used this form may be necessary for python programs that are to be run by web serverthe interaction between the user and the console is handled by "shellprogram the distinction between the console and the shell does not concern us hereso we use the terms interchangeably |
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/local/bin or installed under $homethe shebang line is not needed (but is harmlessunder windowsall the examples in this book have shebang line of the second formalthough we won' show it note that for unix systems we assume that the name of python ' executable (or soft link to itin the path is python if this is not the caseyou will need to change the shebang line in the examples to use the correct name (or correct name and path if you use the first form)or create soft link from the python executable to the name python somewhere in the path obtaining and installing python many powerful plain text editorssuch as vim and emacscome with built-in support for editing python programs this support typically involves providing color syntax highlighting and correctly indenting or unindenting lines an alternative is to use the idle python programming environment on windows and mac os xidle is installed by default on unixes idle is built along with the python interpreter if you build from the tarballbut if you use package manageridle is usually provided as separate package as described in the introduction as the screenshot in figure showsidle has rather retro look that harks back to the days of motif on unix and windows this is because it uses the tk-based tkinter gui library (covered in rather than one of the more powerful modern gui libraries such as pygtkpyqtor wxpython the reasons for the use of tkinter are mixture of historyliberal license conditionsand the fact that tkinter is much smaller than the other gui libraries on the plus sideidle comes as standard with python and is very simple to learn and use idle provides three key facilitiesthe ability to enter python expressions and code and to see the results directly in the python shella code editor that provides python-specific color syntax highlighting and indentation supportand debugger that can be used to step through code to help identify and kill bugs the python shell is especially useful for trying out simple algorithmssnippets of codeand regular expressionsand can also be used as very powerful and flexible calculator several other python development environments are availablebut we recommend that you use idleat least at first an alternative is to create your programs in the plain text editor of your choice and debug using calls to print(it is possible to invoke the python interpreter without specifying python program if this is done the interpreter starts up in interactive mode in this mode it is possible to enter python statements and see the results exactly the same as when using idle' python shell windowand with the same |
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 to create and run python programsbut clearly we won' get very far knowing only single function in the next section we will considerably increase our python knowledge this will make us able to create short but useful python programssomething we will do in this last section python' "beautiful heart||in this section we will learn about eight key pieces of pythonand in the next section we will show how these pieces can be used to write couple of small but realistic programs there is much more to say about all of the things covered in this sectionso if as you read it you feel that python is missing something or that things are sometimes done in long-winded waypeek ahead using the forward references or using the table of contents or indexand you will almost certainly find that python has the feature you want and often has more concise forms of expression than we show here--and lot more besides piece # data types |one fundamental thing that any programming language must be able to do is represent items of data python provides several built-in data typesbut we will concern ourselves with only two of them for now python represents |
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' integers is limited only by machine memorynot by fixed number of bytes strings can be delimited by double or single quotesas long as the same kind are used at both endsand since python uses unicodestrings are not limited to ascii charactersas the penultimate string shows an empty string is simply one with nothing between the delimiters python uses square brackets ([]to access an item from sequence such as string for exampleif we are in python shell (either in the interactive interpreteror in idlewe can enter the following--the python shell' output is shown in lightfacewhat you type is shown in bold"hard times"[ ' "giraffe"[ 'gtraditionallypython shells use as their promptalthough this can be changed the square brackets syntax can be used with data items of any data type that is sequencesuch as strings and lists this consistency of syntax is one of the reasons that python is so beautiful note that all python index positions start at in pythonboth str and the basic numeric types such as int are immutable--that isonce settheir value cannot be changed at first this appears to be rather strange limitationbut python' syntax means that this is nonissue in practice the only reason for mentioning it is that although we can use square brackets to retrieve the character at given index position in stringwe cannot use them to set new character (note that in python character is simply string of length to convert data item from one type to another we can use the syntax datatype(itemfor exampleint(" " |
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 they make senseas we will see in if conversion failsan exception is raised--we briefly introduce exception-handling in piece # and fully cover exceptions in strings and integers are fully covered in along with other built-in data types and some data types from python' standard library that also covers operations that can be applied to immutable sequencessuch as strings piece # object references |once we have some data typesthe next thing we need are variables in which to store them python doesn' have variables as suchbut instead has object references when it comes to immutable objects like ints and strsthere is no discernable difference between variable and an object reference as for mutable objectsthere is differencebut it rarely matters in practice we will use the terms variable and object reference interchangeably let' look at few tiny examplesand then discuss some of the details "bluey "greenz the syntax is simply objectreference value there is no need for predeclaration and no need to specify the value' type when python executes the first statement it creates str object with the text "blue"and creates an object reference called that refers to the str object for all practical purposes we can say that "variable has been assigned the 'bluestringthe second statement is similar the third statement creates new object reference called and sets it to refer to the same object that the object reference refers to (in this case the str containing the text "blue"the operator is not the same as the variable assignment operator in some other languages the operator binds an object reference to an object in memory if the object reference already existsit is simply re-bound to refer to the object on the right of the operatorif the object reference does not exist it is created by the operator shallow and deep copying |
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 new str of value "north"and the int object is scheduled for garbage collection since now no object reference refers to it at this point using with route would cause typeerror to be raised since is not valid operation for string the type(function returns the data type (also known as the "class"of the data item it is given--this function can be very useful for testing and debuggingbut would not normally appear in production codesince there is better alternative as we will see in if we are experimenting with python code inside the interactive interpreter or in python shell such as the one provided by idlesimply typing the name of an object reference is enough to have python print its value for examplex "bluey "greenz 'bluexyz ('blue''green''blue'this is much more convenient than having to call the print(function all the timebut works only when using python interactively--any programs and modules that we write must use print(or similar functions to produce output notice that python displayed the last output in parentheses separated by commas--this signifies tuplethat isan ordered immutable sequence of objects we will cover tuples in the next piece piece # collection data types |it is often convenient to hold entire collections of data items python provides several collection data types that can hold itemsincluding associative arrays and sets but here we will introduce just twotuple and list python tuples and lists can be used to hold any number of data items of any data types tuples are immutableso once they are created we cannot change them lists are mutableso we can easily insert items and remove items whenever we want tuples are created using commas (,)as these examples show--and note that hereand from now onwe don' use bold to distinguish what you type"denmark""finland""norway""sweden('denmark''finland''norway''sweden'isinstance( |
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 is also used to separate arguments in function callsso if we want to pass tuple literal as an argument we must enclose it in parentheses to avoid confusion tuple here are some example lists type creating and calling functions [ ['alpha''bravo''charlie''delta''echo'['zebra' - 'aardvark' [one way to create list is to use square brackets ([]as we have done herelater on we will see other ways the fourth list shown is an empty list under the hoodlists and tuples don' store data items at allbut rather object references when lists and tuples are created (and when items are inserted in the case of lists)they take copies of the object references they are given in the case of literal items such as integers or stringsan object of the appropriate data type is created in memory and suitably initializedand then an object reference referring to the object is createdand it is this object reference that is put in the list or tuple like everything else in pythoncollection data types are objectsso we can nest collection data types inside other collection data typesfor exampleto create lists of listswithout formality in some situations the fact that liststuplesand most of python' other collection data types hold object references rather than objects makes difference--this is covered in in procedural programming we call functions and often pass in data items as arguments for examplewe have already seen the print(function another frequently used python function is len()which takes single data item as its argument and returns the "lengthof the item as an int here are few calls to len()len(("one",) len([ "pause" ] len("automatically" list type shallow and deep copying |
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 called instancesof particular data type (also called classwe will use the terms data type and class interchangeably one key difference between an objectand the plain items of data that some other languages provide ( +or java' built-in numeric types)is that an object can have methods essentiallya method is simply function that is called for particular object for examplethe list type has an append(methodso we can append an object to list like thisx ["zebra" - "aardvark" append("more" ['zebra' - 'aardvark' 'more'the object knows that it is list (all python objects know what their own data type is)so we don' need to specify the data type explicitly in the implementation of the append(method the first argument will be the object itself--this is done automatically by python as part of its syntactic support for methods the append(method mutatesthat ischangesthe original list this is possible because lists are mutable it is also potentially more efficient than creating new list with the original items and the extra item and then rebinding the object reference to the new listparticularly for very long lists in procedural language the same thing could be achieved by using the list' append(like this (which is perfectly valid python syntax)list append( "extra" ['zebra' - 'aardvark' 'more''extra'here we specify the data type and the data type' methodand give as the first argument the data item of the data type we want to call the method onfollowed by any additional arguments (in the face of inheritance there is subtle semantic difference between the two syntaxesthe first form is the one that is most commonly used in practice inheritance is covered in if you are unfamiliar with object-oriented programming this may seem bit strange at first for nowjust accept that python has conventional functions called like thisfunctionname(arguments)and methods which are called like thisobjectname methodname(arguments(object-oriented programming is covered in sized |
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 the particular attribute we want the list type has many other methodsincluding insert(which is used to insert an item at given index positionand remove(which removes an item at given index position as noted earlierpython indexes are always -based we saw before that we can get characters from strings using the square brackets operatorand noted at the time that this operator could be used with any sequence lists are sequencesso we can do things like thisx ['zebra' - 'aardvark' 'more''extra' [ 'zebrax[ tuples are also sequencesso if had been tuple we could retrieve items using square brackets in exactly the same way as we have done for the list but since lists are mutable (unlike strings and tuples which are immutable)we can also use the square brackets operator to set list elements for examplex[ "forty ninex ['zebra''forty nine'- 'aardvark' 'more''extra'if we give an index position that is out of rangean exception will be raised--we briefly introduce exception-handling in piece # and fully cover exceptions in we have used the term sequence few times nowrelying on an informal understanding of its meaningand will continue to do so for the time being howeverpython defines precisely what features sequence must supportand similarly defines what features sized object must supportand so on for various other categories that data type might belong toas we will see in liststuplesand python' other built-in collection data types are covered in piece # logical operations |one of the fundamental features of any programming language is its logical operations python provides four sets of logical operationsand we will review the fundamentals of all of them here |
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 referring to the same object as its right-hand object reference here are some examplesa ["retention" noneb ["retention" nonea is false is true note that it usually does not make sense to use is for comparing intsstrsand most other data types since we almost invariably want to compare their values in factusing is to compare data items can lead to unintuitive resultsas we can see in the preceding examplewhere although and are initially set to the same list valuesthe lists themselves are held as separate list objects and so is returns false the first time we use it one benefit of identity comparisons is that they are very fast this is because the objects referred to do not have to be examined themselves the is operator needs to compare only the memory addresses of the objects--the same address means the same object the most common use case for is is to compare data item with the built-in null objectnonewhich is often used as place-marking value to signify "unknownor "nonexistent" "somethingb none is not noneb is none (truetrueto invert the identity test we use is not the purpose of the identity operator is to see whether two object references refer to the same objector to see whether an object is none if we want to compare object values we should use comparison operator instead comparison operators python provides the standard set of binary comparison operatorswith the expected semanticsless than<less than or equal to=equal to!not |
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 compare properly tooa "many pathsb "many pathsa is false = true although and are different objects (have different identities)they have the same valuesso they compare equal be awarethoughthat because python uses unicode for representing stringscomparing strings that contain non-ascii characters can be lot subtler and more complicated than it might at first appear--we will fully discuss this issue in in some casescomparing the identity of two strings or numbers--for exampleusing is --will return trueeven if each has been assigned separately as we did here this is because some implementations of python will reuse the same object (since the value is the same and is immutablefor the sake of efficiency the moral of this is to use =and !when comparing valuesand to use is and is not only when comparing with none or when we really do want to see if two object referencesrather than their valuesare the same one particularly nice feature of python' comparison operators is that they can be chained for examplea < < true this is nicer way of testing that given data item is in range than having to do two separate comparisons joined by logical andas most other languages require it also has the additional virtue of evaluating the data item only once (since it appears once only in the expression)something that could make comparing strings |
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 last)typeerrorunorderable typesstr(int(when an exception is raised and not handledpython outputs traceback along with the exception' error message for claritywe have omitted the traceback part of the outputreplacing it with an ellipsis the same typeerror exception would occur if we wrote " because python does not try to guess our intentions--the right approach is either to explicitly convertfor exampleint(" " or to use comparable typesthat isboth integers or both strings python makes it easy for us to create custom data types that will integrate nicely so thatfor examplewe could create our own custom numeric type which would be able to participate in comparisons with the built-in int typeand with other built-in or custom numeric typesbut not with strings or other non-numeric types the membership operator for data types that are sequences or collections such as stringslistsand tupleswe can test for membership using the in operatorand for nonmembership using the not in operator for examplep ( "frog" - in true "dognot in true for lists and tuplesthe in operator uses linear search which can be slow for very large collections (tens of thousands of items or moreon the other handin is very fast when used on dictionary or setboth of these collection data types are covered in here is how in can be used with stringphrase "wild swans by jung chang"jin phrase true traceback (sometimes called backtraceis list of all the calls made from the point where the unhandled exception occurred back to the top of the call stack dealing with runtime errors alternative fuzzybool |
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 determined the result--they do not return boolean (unless they actually have boolean operandslet' see what this means in practicefive two zero five and two two and five five and zero if the expression occurs in boolean contextthe result is evaluated as booleanso the preceding expressions would come out as truetrueand false insayan if statement nought five or two two or five zero or five zero or nought the or operator is similarhere the results in boolean context would be truetruetrueand false the not unary operator evaluates its argument in boolean context and always returns boolean resultso to continue the earlier examplenot (zero or noughtwould produce trueand not two would produce false |
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 conditional branch or loop statement control is also diverted when an exception is raised in this subsection we will look at python' if statement and its while and for loopsdeferring consideration of functions to piece # and methods to we will also look at the very basics of exception-handlingwe cover the subject fully in but first we will clarify couple of items of terminology boolean expression is anything that can be evaluated to produce boolean value (true or falsein pythonsuch an expression evaluates to false if it is the predefined constant falsethe special object nonean empty sequence or collection ( an empty stringlistor tuple)or numeric data item of value anything else is considered to be true when we create our own custom data types ( in )we can decide for ourselves what they should return in boolean context in python-speak block of codethat isa sequence of one or more statementsis called suite because some of python' syntax requires that suite be presentpython provides the keyword pass which is statement that does nothing and that can be used where suite is required (or where we want to indicate that we have considered particular casebut where no processing is necessary the if statement the general syntax for python' if statement is thisif boolean_expression suite elif boolean_expression suite elif boolean_expressionnsuiten elseelse_suite in this bookellipses are used to indicate lines that are not shown |
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 notice is the colonthis is part of the syntax and is easy to forget at first colons are used with elseelifand essentially in any other place where suite is to follow unlike most other programming languagespython uses indentation to signify its block structure some programmers don' like thisespecially before they have tried itand some get quite emotional about the issue but it takes just few days to get used toand after few weeks or monthsbrace-free code seems much nicer and less cluttered to read than code that uses braces since suites are indicated using indentationthe question that naturally arises is"what kind of indentation?the python style guidelines recommend four spaces per level of indentationand only spaces (no tabsmost modern text editors can be set up to handle this automatically (idle' editor does of courseand so do most other python-aware editorspython will work fine with any number of spaces or with tabs or with mixture of bothproviding that the indentation used is consistent in this bookwe follow the official python guidelines here is very simple if statement exampleif xprint(" is nonzero"in this caseif the condition (xevaluates to truethe suite (the print(function callwill be executed if lines print("small"elif lines print("medium"elseprint("large"this is slightly more elaborate if statement that prints word that describes the value of the lines variable the while statement the while statement is used to execute suite zero or more timesthe number of times depending on the state of the while loop' boolean expression here' the syntax |
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 loop in which the break statement appears--that isit breaks out of the loop the continue statement switches control to the start of the loop both break and continue are normally used inside if statements to conditionally change loop' behavior while trueitem get_next_item(if not itembreak process_item(itemthis while loop has very typical structure and runs as long as there are items to process (both get_next_item(and process_item(are assumed to be custom functions defined elsewhere in this examplethe while statement' suite contains an if statementwhich itself has suite--as it must--in this case consisting of single break statement the for in statement python' for loop reuses the in keyword (which in other contexts is the membership operator)and has the following syntaxfor variable in iterablesuite just like the while loopthe for loop supports both break and continueand also has an optional else clause the variable is set to refer to each object in the iterable in turn an iterable is any data type that can be iterated overand includes strings (where the iteration is character by character)liststuplesand python' other collection data types for country in ["denmark""finland""norway""sweden"]print(countryhere we take very simplistic approach to printing list of countries in practice it is much more common to use variablecountries ["denmark""finland""norway""sweden"for country in countriesprint(country |
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 vowel"elseprint(letter"is consonant"in this snippet the first use of the in keyword is part of for statementwith the variable letter taking on the values " "" "and so on up to " "changing at each iteration of the loop on the snippet' second line we use in againbut this time as the membership testing operator notice also that this example shows nested suites the for loop' suite is the if else statementand both the if and the else branches have their own suites basic exception handling many of python' functions and methods indicate errors or other important events by raising an exception an exception is an object like any other python objectand when converted to string ( when printed)the exception produces message text simple form of the syntax for exception handlers is thistrytry_suite except exception as variable exception_suite except exceptionn as variablenexception_suiten note that the as variable part is optionalwe may care only that particular exception was raised and not be interested in its message text the full syntax is more sophisticatedfor exampleeach except clause can handle multiple exceptionsand there is an optional else clause all of this is covered in the logic works like this if the statements in the try block' suite all execute without raising an exceptionthe except blocks are skipped if an exception is raised inside the try blockcontrol is immediately passed to the suite corresponding to the first matching exception--this means that any statements in the suite that follow the one that caused the exception will not be executed if list comprehensions |
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 placepython looks for matching except block in the next enclosing scope the search for suitable exception handler works outward in scope and up the call stack until either match is found and the exception is handledor no match is foundin which case the program terminates with an unhandled exception in the case of an unhandled exceptionpython prints traceback as well as the exception' message text here is an examples input("enter an integer"tryi int(sprint("valid integer entered:"iexcept valueerror as errprint(errif the user enters " "the output will beinvalid literal for int(with base ' but if they were to enter " "the output will bevalid integer entered many books consider exception-handling to be an advanced topic and defer it as late as possible but raising and especially handling exceptions is fundamental to the way python worksso we make use of it from the beginning and as we shall seeusing exception handlers can make code much more readableby separating the "exceptionalcases from the processing we are really interested in piece # arithmetic operators |python provides full set of arithmetic operatorsincluding binary operators for the four basic mathematical operationsadditionsubtractionmultiplicationand division in additionmany python data types can be used with augmented assignment operators such as +and *the +-and operators all behave as expected when both of their operands are integers dealing with runtime errors |
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 integertruncating any fractional part if we need an integer resultwe can always convert using int((or use the truncating division operator //discussed latera + at first sight the preceding statements are unsurprisingparticularly to those familiar with -like languages in such languagesaugmented assignment is shorthand for assigning the results of an operation--for examplea + is essentially the same as howeverthere are two important subtleties hereone python-specific and one to do with augmented operators in any language the first point to remember is that the int data type is immutable--that isonce assignedan int' value cannot be changed sowhat actually happens behind the scenes when an augmented assignment operator is used on an immutable object is that the operation is performedand an object holding the result is createdand then the target object reference is re-bound to refer to the result object rather than the object it referred to before soin the preceding case when the statement + is encounteredpython computes stores the result in new int objectand then rebinds to refer to this new int (and if the original object was referring to has no more object references referring to itit will be scheduled for garbage collection figure illustrates this point the second subtlety is that operatorb is not quite the same as operator the augmented version looks up ' value only onceso it is potentially faster alsoif is complex expression ( list element with an index position calculation such as items[offset index])using the augmented version may numeric operators and functions |
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 list +operator must be an iterableif it is not an exception is raisedseeds + traceback (most recent call last)typeerror'intobject is not iterable the correct way to extend list is to use an iterable objectsuch as listseeds +[ seeds ['sesame''sunflower''pumpkin' and of coursethe iterable object used to extend the list can itself have more than one itemseeds +[ "poppy"seeds ['sesame''sunflower''pumpkin' 'poppy'appending plain string--for example"durian"--rather than list containing string["durian"]leads to logical but perhaps surprising resultseeds ["sesame""sunflower""pumpkin"seeds +"durianseeds ['sesame''sunflower''pumpkin'' '' '' '' '' '' 'the list +operator extends the list by appending each item of the iterable it is provided withand since string is an iterablethis leads to each character in the string being appended individually if we use the list append(methodthe argument is always added as single item piece # input/output dealing with runtime errors |to be able to write genuinely useful programs we must be able to read input--for examplefrom the user at the consoleand from files--and produce outputeither to the console or to files we have already made use of python' built-in print(functionalthough we will defer covering it further until chap |
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 waits for the user to type in response and to finish by pressing enter (or returnif the user does not type any text but just presses enterthe input(function returns an empty stringotherwiseit returns string containing what the user typedwithout any line terminator here is our first complete "usefulprogramit draws on many of the previous pieces--the only new thing it shows is the input(functionprint("type integerseach followed by enteror just enter to finish"total count while trueline input("integer"if linetrynumber int(lineexcept valueerror as errprint(errcontinue total +number count + elsebreak if countprint("count ="count"total ="total"mean ="total countbook' examples the program (in file sum py in the book' exampleshas just executable lines here is what typical run looks liketype integerseach followed by enteror just enter to finish number number number invalid literal for int(with base ' xnumber number numbercount total mean although the program is very shortit is fairly robust if the user enters string that cannot be converted to an integerthe problem is caught by an |
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 by redirecting the print(functionsoutput from the console for examplec:\>test py results txt windows file association bug will cause the output of plain print(function calls made in the fictitious test py program to be written to the file results txt this syntax works in the windows console (usuallyand in unix consoles for windowswe must write :\python \python exe test py results txt if python is the machine' default python version or if the console exhibits the file association bugotherwiseassuming python is in the pathpython test py results txt should be sufficientif plain test py results txt doesn' work for unixes we must make the program executable (chmod + test pyand then invoke it by typing /test py unless the directory it is in happens to be in the pathin which case invoking it by typing test py is sufficient reading data can be achieved by redirecting file of data as input in an analogous way to redirecting output howeverif we used redirection with sum pythe program would fail this is because the input(function raises an exception if it receives an eof (end of filecharacter here is more robust version (sum pythat can accept input from the user typing at the keyboardor via file redirectionprint("type integerseach followed by enteror ^ or ^ to finish"total count while truetryline input(if linenumber int(linetotal +number count + except valueerror as errprint(errcontinue except eoferrorbreak if countprint("count ="count"total ="total"mean ="total count |
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 changes to make the program more suitable for use both interactively and using redirection firstwe have changed the termination from being blank line to the eof character (ctrl+ on unixctrl+zenter on windowsthis makes the program more robust when it comes to handling input files that contain blank lines we have stopped printing prompt for each number since it doesn' make sense to have one for redirected input and we have also used single try block with two exception handlers notice that if an invalid integer is entered (either via the keyboard or due to "badline of data in redirected input file)the int(conversion will raise valueerror exception and the flow of control will immediately switch to the relevant except block--this means that neither total nor count will be incremented when invalid data is encounteredwhich is exactly what we want we could just as easily have used two separate exception-handling try blocks insteadwhile truetryline input(if linetrynumber int(lineexcept valueerror as errprint(errcontinue total +number count + except eoferrorbreak but we preferred to group the exceptions together at the end to keep the main processing as uncluttered as possible piece # creating and calling functions |it is perfectly possible to write programs using the data types and control structures that we have covered in the preceding pieces howeververy often we want to do essentially the same processing repeatedlybut with small differencesuch as different starting value python provides means of encapsu |
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 from the function using the syntax return valuein which case value is returned the return value can be just one value or tuple of values the return value can be ignored by the callerin which case it is simply thrown away note that def is statement that works in similar way to the assignment operator when def is executed function object is created and an object reference with the specified name is created and set to refer to the function object since functions are objectsthey can be stored in collection data types and passed as arguments to other functionsas we will see in later one frequent need when writing interactive console applications is to obtain an integer from the user here is function that does just thatdef get_int(msg)while truetryi int(input(msg)return except valueerror as errprint(errthis function takes one argumentmsg inside the while loop the user is prompted to enter an integer if they enter something invalid valueerror exception will be raisedthe error message will be printedand the loop will repeat once valid integer is enteredit is returned to the caller here is how we would call itage get_int("enter your age"in this example the single argument is mandatory because we have provided no default value in factpython supports very sophisticated and flexible syntax for function parameters that supports default argument values and positional and keyword arguments all of the syntax is covered in although creating our own functions can be very satisfyingin many cases it is not necessary this is because python has lot of functions built inand great many more functions in the modules in its standard libraryso what we want may well already be available return statement |
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 the name of the py filebut omitting the extension once module has been importedwe can access any functionsclassesor variables that it contains for exampleprint(sys argvthe sys module provides the argv variable-- list whose first item is the name under which the program was invoked and whose second and subsequent items are the program' command-line arguments the two previously quoted lines constitute the entire echoargs py program if the program is invoked with the command line echoargs py -vit will print ['echoargs py''- 'on the console (on unix the first entry may be /echoargs pydot operator in generalthe syntax for using function from module is modulename functionname(argumentsit makes use of the dot ("access attribute"operator we introduced in piece # the standard library contains lots of modulesand we will make use of many of them throughout the book the standard modules all have lowercase namesso some programmers use title-case names ( mymodulefor their own modules to keep them distinct let us look at just one examplethe random module (in the standard library' random py file)which provides many useful functionsimport random random randint( random choice(["apple""banana""cherry""durian"]after these statements have been executedx will contain an integer between and inclusiveand will contain one of the strings from the list passed to the random choice(function shebang (#!line it is conventional to put all the import statements at the beginning of py filesafter the shebang lineand after the module' documentation (documenting modules is covered in we recommend importing standard library modules firstthen third-party library modulesand finally your own modules the sys modulesome other built-in modulesand modules implemented in don' necessarily have corresponding py files--but they are used in just the same way as those that do |
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 python' language and libraryso that we will be able to write programs that are more concise and more robust than those shown here--but first we must have the foundations on which to build |bigdigits py the first program we will review is quite shortalthough it has some subtle aspectsincluding list of lists here is what it doesgiven number on the command linethe program outputs the same number onto the console using "bigdigits at sites where lots of users share high-speed line printerit used to be common practice for each user' print job to be preceded by cover page that showed their username and some other identifying details printed using this kind of technique we will review the code in three partsthe importthe creation of the lists holding the data the program usesand the processing itself but firstlet' look at sample runbigdigits py **************************************we have not shown the console prompt (or the leading for unix users)we will take them for granted from now on import sys since we must read in an argument from the command line (the number to output)we need to access the sys argv listso we begin by importing the sys module we represent each number as list of strings for examplehere is zero |
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 listor multiline statement where every end-of-line character except the last is escaped by preceding it with backslash (\in all these cases any number of lines can be spanned and indentation does not matter for the second and subsequent lines each list representing number has seven stringsall of uniform widthalthough what this width is differs from number to number the lists for the other numbers follow the same pattern as for zeroalthough they are laid out for compactness rather than for clarityone [""*""""""***"two [**""*""""""nine [****""*""*"****"*"""*****"*"*"the last piece of data we need is list of all the lists of digitsdigits [zeroonetwothreefourfivesixseveneightninewe could have created the digits lists directlyand avoided creating the extra variables for exampledigits [**"""*""*""*""**"]zero [""*""""""***"]one [****""*""*"****"*"*"*"nine we preferred to use separate variable for each number both for ease of understanding and because it looks neater using the variables we will quote the rest of the code in one go so that you can try to figure out how it works before reading the explanation that follows set type dict type |
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 that can go wrong we begin by retrieving the program' command-line argument the sys argv list is -based like all python liststhe item at index position is the name the program was invoked asso in running program this list always starts out with at least one item if no argument was given we will be trying to access the second item in one-item list and this will cause an indexerror exception to be raised if this occursthe flow of control is immediately switched to the corresponding exception-handling blockand there we simply print the program' usage execution then continues after the end of the try blockbut there is no more codeso the program simply terminates if no indexerror occursthe digits string holds the command-line argumentwhich we hope is sequence of digit characters (remember from piece # that identifiers are case-sensitiveso digits and digits are different each big digit is represented by seven stringsand to output the number correctly we must output the top row of every digitthen the next rowand so onuntil all seven rows have been output we use while loop to iterate over each row we could just as easily have done this insteadfor row in ( )and later on we will see much better way using the built-in range(function we use the line string to hold the row strings from all the digits involved then we loop by columnthat isby each successive character in the command-line argument we retrieve each character with digits[columnand convert the digit to an integer called number if the conversion fails valueerror exception is raised and the flow of control immediately switches to the corresponding exception handler in this case we print an error messageand control resumes after the try block as noted earliersince there is no more code at this pointthe program will simply terminate range( |
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 each time the inner while loop finisheswe print the line that has been built up the key to understanding this program is where we append each digit' row string to the current row' line try running the program to get feel for how it works we will return to this program in the exercises to improve its output slightly |generate_grid py one frequently occurring need is the generation of test data there is no single generic program for doing thissince test data varies enormously python is often used to produce test data because it is so easy to write and modify python programs in this subsection we will create program that generates grid of random integersthe user can specify how many rows and columns they want and over what range the integers should span we'll start by looking at sample rungenerate_grid py rows invalid literal for int(with base ' xrows columns minimum (or enter for )- maximum (or enter for ) - - - - - the program works interactivelyand at the beginning we made typing error when entering the number of rows the program responded by printing an error message and then asking us to enter the number of rows again for the maximum we just pressed enter to accept the default we will review the code in four partsthe importthe definition of get_int(function ( more sophisticated version than the one shown in piece # )the user interaction to get the values to useand the processing itself import random random randint( we need the random module to give us access to the random randint(function |
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 are two possibilities if default is nonethat isno default value has been giventhe flow of control will drop through to the int(line there the conversion will fail (since 'cannot be converted to an integer)and valueerror exception will be raised but if default is not nonethen it is returned otherwisethe function will attempt to convert the text the user entered into an integerand if the conversion is successfulit will then check that the integer is at least equal to the minimum that has been specified sothe function will always return either default (if the user just pressed enter)or valid integer that is greater than or equal to the specified minimum rows get_int("rows" nonecolumns get_int("columns" noneminimum get_int("minimum (or enter for )"- default if default minimumdefault minimum maximum get_int("maximum (or enter for str(default")"minimumdefaultour get_int(function makes it easy to obtain the number of rows and columns and the minimum random value that the user wants for rows and columns we give default value of nonemeaning no defaultso the user must enter an integer in the case of the minimumwe supply default value of and for the maximum we give default value of or twice the minimum if the minimum is greater than or equal to as we noted in the previous examplefunction call argument lists can span any number of linesand indentation is irrelevant for their second and subsequent lines |
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 + print(linerow + to generate the grid we use three while loopsthe outer one working by rowsthe middle one by columnsand the inner one by characters in the middle loop we obtain random number in the specified range and then convert it to string the inner while loop is used to pad the string with leading spaces so that each number is represented by string characters wide we use the line string to accumulate the numbers for each rowand print the line after each column' numbers have been added this completes our second example python provides very sophisticated string formatting functionalityas well as excellent support for for in loopsso more realistic versions of both bigdigits py and generate_grid py would have used for in loopsand generate_grid py would have used python' string formatting capabilities rather than crudely padding with spaces but we have limited ourselves to the eight pieces of python introduced in this and they are quite sufficient for writing complete and useful programs in each subsequent we will learn new python featuresso as we progress through the book the programs we will see and be capable of writing will grow in sophistication summary ||in this we learned how to edit and run python programs and reviewed few small but complete programs but most of the pages were devoted to the eight pieces of python' "beautiful heart"--enough of python to write real programs we began with two of python' most basic data typesint and str integer literals are written just as they are in most other programming languages string str format( |
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 are sequencesso those functions and operations that can be used with sequences can be used with strings for examplewe can access particular character using the item access operator ([])concatenate strings using +and append one string to another using +since strings are immutablebehind the scenesappending creates new string that is the concatenation of the given stringsand rebinds the left-hand string object reference to the resultant string we can also iterate over string character by character using for in loop and we can use the built-in len(function to report how many characters are in string for immutable objects like stringsintegersand tupleswe can write our code as though an object reference is variablethat isas though an object reference is the object it refers to we can also do this for mutable objectsalthough any change made to mutable object will affect all occurrences of the object ( all object references to the object)we will cover this issue in python provides several built-in collection data types and has some others in its standard library we learned about the list and tuple typesand in particular how to create tuples and lists from literalsfor exampleeven [ listslike everything else in pythonare objectsso we can call methods on them--for exampleeven append( will add an extra item to the list like stringslists and tuples are sequencesso we can iterate over them item by item using for in loopand find out how many items they have using len(we can also retrieve particular item in list or tuple using the item access operator ([])concatenate two lists or tuples using +and append one to another using +if we want to append single item to list we must either use list append(or use +with the item made into single-item list--for exampleeven +[ since lists are mutablewe can use [to change individual itemsfor exampleeven[ the fast is and is not identity operators can be used to check whether two object references refer to the same thing--this is particularly useful when checking against the unique built-in none object all the usual comparison operators are available (=>)but they can be used only with compatible data typesand then only if the operations are supported the data types we have seen so far--intstrlistand tuple--all support the complete set of comparison operators comparing incompatible typesfor examplecomparing an int with str or listwill quite sensibly produce typeerror exception python supports the standard logical operators andorand not both and and or are short-circuit operators that return the operand that determined their |
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 lists and tuplesand potentially much faster hybrid algorithm for stringsbut performance is rarely an issue except for very long stringslistsand tuples in we will learn about python' associative array and set collection data typesboth of which provide very fast membership testing it is also possible to find out an object variable' type ( the type of object the object reference refers tousing type()--but this function is normally used only for debugging and testing python provides several control structuresincluding conditional branching with if elif elseconditional looping with whilelooping over sequences with for inand exception-handling with try except blocks both while and for in loops can be prematurely terminated using break statementand both can switch control to the beginning using continue the usual arithmetic operators are supportedincluding +-*and /although python is unusual in that always produces floating-point result even if both its operands are integers (the truncating division that many other languages use is also available in python as /python also provides augmented assignment operators such as +and *=these create new objects and rebind behind the scenes if their left-hand operand is immutable the arithmetic operators are overloaded by the str and list types as we noted earlier console / can be achieved using input(and print()and using file redirection in the consolewe can use these same built-in functions to read and write files in addition to python' rich built-in functionalityits extensive standard library is also availablewith modules accessible once they have been imported using the import statement one commonly imported module is syswhich holds the sys argv list of command-line arguments and when python doesn' have the function we need we can easily create one that does what we want using the def statement by making use of the functionality described in this it is possible to write short but useful python programs in the following we will learn more about python' data typesgoing into more depth for ints and strs and introducing some entirely new data types in we will learn more about tuples and listsand also about some of python' other collection data types thenin we will cover python' control structures in much more detailand will learn how to create our own functions so that we can package up functionality to avoid code duplication and promote code reuse |
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 kept fairly small so that the emphasis is on thinking and learning rather than just typing code every exercise has solution provided with the book' examples one nice variation of the bigdigits py program is where instead of printing *sthe relevant digit is printed instead for examplebigdigits_ans py two approaches can be taken the easiest is to simply change the * in the lists but this isn' very versatile and is not the approach you should take insteadchange the processing code so that rather than adding each digit' row string to the line in one goyou add character by characterand whenever is encountered you use the relevant digit this can be done by copying bigdigits py and changing about five lines it isn' hardbut it is slightly subtle solution is provided as bigdigits_ans py idle can be used as very powerful and flexible calculatorbut sometimes it is useful to have task-specific calculator create program that prompts the user to enter number in while loopgradually building up list of the numbers entered when the user has finished (by simply pressing enter)print out the numbers they enteredthe count of numbersthe sum of the numbersthe lowest and highest numbers enteredand the mean of the numbers (sum counthere is sample runaverage _ans py enter number or enter to finish enter number or enter to finish enter number or enter to finish enter number or enter to finish enter number or enter to finish enter number or enter to finish enter number or enter to finish |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.