id
int64
0
25.6k
text
stringlengths
0
4.59k
600
casesyou can witness the effect of program change nearly as fast as you can type it of coursedevelopment cycle turnaround is only one aspect of python' ease of use it also provides deliberately simple syntax and powerful built-in tools in factsome have gone so far as to call python executable pseudocode because it elim...
601
the traditional "fooand "barfor generic variable names become "spamand "eggsin the python world the occasional "brian,"ni,and "shrubberylikewise owe their appearances to this namesake it even impacts the python community at largesome events at python conferences are regularly billed as "the spanish inquisition all of t...
602
is richer language that is used more widelyand its open source nature means it is not controlled by single company is more readable and general-purpose than php python is used to construct websites toobut it is also applied to nearly every other computer domainfrom robotics to movie animation and gaming is more powerfu...
603
won' really start programming per se until but make sure you have handle on the startup details before moving on test your knowledgequiz in this edition of the bookwe will be closing each with quick open-book quiz about the material presented herein to help you review the key concepts the answers for these quizzes appe...
604
linked-in code in the interpreter if speed is criticalcompiled extensions are available for number-crunching parts of an application you can use python for nearly anything you can do with computerfrom website development and gaming to robotics and spacecraft control this was mentioned in footnoteimport this triggers an...
605
themselvesthe prospect of someone else changing their work later doesn' enter into it this is critical difference between art and engineering when people write softwarethey are not writing it for themselves in factthey are not even writing primarily for the computer rathergood programmers know that code is written for ...
606
how python runs programs this and the next take quick look at program execution--how you launch codeand how python runs it in this we'll study how the python interpreter executes programs in general will then show you how to get your own programs up and running startup details are inherently platform-specificand some o...
607
windows users fetch and run self-installing executable file that puts python on their machines simply double-click and say yes or next at all prompts linux and mac os users probably already have usable python preinstalled on their computers--it' standard component on these platforms today some linux and mac os users (a...
608
button menu this can vary across releasesbut idle starts development guiand python starts simple interactive session also here are the standard manuals and the pydoc documentation engine (module docssee and appendix for pointers on windows and other platforms in getting it to run 'll explain the print statementand why ...
609
for examplehere' what happened when ran this script from command prompt window' command line on windows laptopto make sure it didn' have any silly typosc:\codepython script py hello world see for the full story on this processespecially if you're new to programmingwe'll get into all the gory details of writing and laun...
610
__pycache__ located in the directory where your source files resideand in files whose names identify the python version that created them ( script cpython- pycthe new __pycache__ subdirectory helps to avoid clutterand the new naming convention for byte code files prevents different python versions installed on the same...
611
codewhich is then run by the python virtual machine your code is automatically compiledbut then it is interpreted pvm sounds more impressive than it isreallyit' not separate programand it need not be installed by itself in factthe pvm is just big code loop that iterates through your byte code instructionsone by oneto c...
612
but in pythonthe compiler is always present at runtime and is part of the system that runs programs this makes for much more rapid development cycle there is no need to precompile and link before execution may beginsimply type and run the code this also adds much more dynamic flavor to the language--it is possibleand o...
613
implement the same python language but execute programs in different ways for examplepypy is drop-in replacement for cpythonwhich can run most programs much quicker similarlyjython and ironpython are completely independent implementations of python that compile python source for different runtime architecturesto provid...
614
less robust than cpythonthoughit is usually seen as tool of interest primarily to java developers looking for scripting language to serve as frontend to java code see jython' website ironpythonpython for net third implementation of pythonand newer than both cpython and jythonironpython is designed to allow python progr...
615
and its microthreads to support massive concurrency pypy is the successor to the original psyco jitdescribed aheadand subsumes it with complete python implementation built for speed jit is really just an extension to the pvm--the rightmost bubble in figure - --that translates portions of your byte code all the way to b...
616
for the arm processorand still python -only implementation per its beta release notes"pypy is very compliant python interpreteralmost drop-in replacement for cpython it' fast due to its integrated tracing jit compiler this release supports machines running linux / mac os or windows it also supports arm machines running...
617
python to codeand it limits python programs to an implicit statically typed constraint that is typical of most programs but is technically not normal pythonso we won' go into further detail here initial resultsthoughshow that it has the potential to outperform both standard python and psyco-like extensions in terms of ...
618
sometimes when people ask for "realpython compilerwhat they're really seeking is simply way to generate standalone binary executables from their python programs this is more packaging and shipping idea than an execution-flow conceptbut it' somewhat related with the help of third-party tools that you can fetch off the w...
619
finallynote that the runtime execution model sketched here is really an artifact of the current implementation of pythonnot of the language itself for instanceit' not impossible that fulltraditional compiler for translating python source code to machine code may appear during the shelf life of this book (although the f...
620
what is the python interpreter what is source code what is byte code what is the pvm name two or more variations on python' standard execution model how are cpythonjythonand ironpython different what are stackless and pypytest your knowledgeanswers the python interpreter is program that runs the python programs you wri...
621
how you run programs okit' time to start running some code now that you have handle on the program execution modelyou're finally ready to start some real python programming at this pointi'll assume that you have python installed on your computerif you don'tsee the start of the prior and appendix for installation and co...
622
perhaps the simplest way to run python programs is to type them at python' interactive command linesometimes called the interactive prompt there are variety of ways to start this command linein an idefrom system consoleand so on assuming the interpreter is installed as an executable program on your systemthe most platf...
623
typing commandsbut they're too specific to get into heresee your system' documentation for details anytime you see the promptyou're in an interactive python interpreter session-you can type any python statement or expression here and run it immediately we will in momentbut first we need to get few startup details sorte...
624
python ( :bd afb ebf sep : : [msc bit type "help""copyright""creditsor "licensefor more information ^ alternativelyyou can run "cdchange-directory command to go to python' install directory before typing python--try the cd :\python command on windowsfor examplec:\codecd :\python :\python python python ( :bd afb ebf sep...
625
^ as shown in the last two commands herethese executables also accept python version numbers on the command line (and in unix-style #lines at the top of scriptsas discussed later)and are associated to open python files when clicked just like the original python executable--which is still available and works as beforebu...
626
on unix-based systems (including mac os and linux)your working directory might be in /usr/home and be created by mkdir command in shell window or file explorer gui specific to your platformbut the same concepts apply the cygwin unix-like system for windows is similar toothough your directory names may vary (/home and /...
627
the launcher later in this and in appendix bif you're working alonginteractive listings will drop most continuation prompts as of to aid cut-and-paste of larger code such as functions and classes from ebooks or otheruntil thenpaste or type one line at time and omit the prompts at least initiallyit' important to type co...
628
use ctrl- (on unixor ctrl- (on windowsto exit herethe first line saves value by assigning it to variable (lumberjack)which is created by the assignmentand the last two lines typed are expressions (lumberjack and * )whose results are displayed automatically againto exit an interactive session like this and return to you...
629
'spam! 'spam!spam!spam!spam!spam!spam!spam!spam!learning by trying the immediate feedback you receive at the interactive prompt is often the quickest way to deduce what piece of code does hereit' clear that it does string repetitionin python means multiply for numbersbut repeat for strings--it' like concatenating strin...
630
type calls to linked-in functionsexercise java classes under jythonand more partly because of its interactive naturepython supports an experimental and exploratory programming style you'll find convenient when getting started although python programmers also test with in-file code (and we'll learn ways to make this sim...
631
main prompt the and prompt strings can also be changed (they are available in the built-in module sys)but 'll assume they have not been in the book' example listings terminate compound statements at the interactive prompt with blank line at the interactive promptinserting blank line (by hitting the enter key at the sta...
632
print(xprint('done'file ""line print('done'syntaxerrorinvalid syntax press enter twice before new statement this means you can' cut and paste multiple lines of code into the interactive promptunless the code includes blank lines after each compound statement such code is better run in file--which brings us to the next ...
633
control over programs first script let' get started open your favorite text editor ( vinotepador the idle editor)type the following statements into new text file named script pyand save it in your working code directory that you set up earliera first python script import sys print(sys platformprint( * 'spam!print( load...
634
once you've saved this text fileyou can ask python to run it by listing its full filename as the first argument to python command like the following typed at the system shell prompt (don' type this at python' interactive promptand read on to the next paragraph if this doesn' work right away for you)python script py win...
635
because this scheme uses shell command lines to start python programsall the usual shell syntax applies for instanceyou can route the printed output of python script to file to save it for later use or inspection by using special shell syntaxpython script py saveit txt in this casethe three output lines shown in the pr...
636
from the one in which you are working for examplethe following system command linerun from :\otherassumes python is in your system path but runs file located elsewherec:\codecd :\other :\otherpython :\code\script py if your path doesn' include python' directoryyou're not using the windows launcher' py programand neithe...
637
file search rules do not apply because of thatyou must include both the py extension andif necessarythe full directory path leading to the file you wish to run for instanceto run file that resides in different directory from the one in which you are workingyou would typically list its full path ( python :\tests \spam p...
638
it to find an interpreter for running the program code in the rest of the file alsonote that this file is called simply brianwithout the py suffix used for the module file earlier adding py to the name wouldn' hurt (and might help you remember that this is python program file)but because you don' plan on letting other ...
639
if you're using python or laterthoughor have its windows launcher installed separatelyit turns out that unix-style #lines do mean something on windows too besides offering the py executable described earlierthe new windows launcher mentioned earlier attempts to parse #lines to determine which python version to launch t...
640
or later on windows or may in the futurei recommend side trip to the full launcher story in appendix if you haven' made one already clicking file icons if you're not fan of command linesyou can generally avoid them by launching python scripts with file icon clicksdevelopment guisand other schemes that vary per platform...
641
to illustratelet' keep using the script we wrote earlierscript pyrepeated here to minimize page flippinga first python script import sys print(sys platformprint( * 'spam!print( load library module raise to power string repetition as we've seenyou can always run this file from system command linec:\codepython script py ...
642
automatically be run with double-click of the mouse (though you might not see printed output or error messages this wayprints and exits--the console window appearsand text is printed therebut the console window closes and disappears on program exit unless you are very fastor your machine is very slowyou won' get to see...
643
if you include an input call at the very end of the script but you only need to do so in this one contextbefore we move aheadnote that the input call applied here is the input counterpart of using the print function (and statementfor outputs it is the simplest way to read user inputand it is more general than this exam...
644
textif you don'tstick to just plain input in and raw_input in other icon-click limitations even with the prior section' input trickclicking file icons is not without its perils you also may not get to see python error messages if your script generates an errorthe error message text is written to the pop-up console wind...
645
import tools from other module files one of the modules is designated as the main or top-level fileor "script"--the file launched to start the entire programwhich runs line by line as usual below this levelit' all modules importing modules we'll delve into such architectural issues in more detail later in this book thi...
646
interactive session in this sessionfor examplethe second print statement in script py was changed in another window to print * between the time of the first import and the reload call--hence the different result the reload function expects the name of an already loaded module objectso you have to have successfully impo...
647
and other programs externallya module file' names can be fetched with two python statementsimport and fromas well as the reload call to illustrateuse text editor to create one-line python module file called myfile py in your working directorywith the following contentstitle "the meaning of lifethis may be one of the wo...
648
classes in your modulessuch objects become reusable software components that can be accessed by name from one or more client modules in practicemodule files usually define more than one name to be used in and outside the files here' an example that defines threea 'deadb 'parrotc 'sketchprint(abcdefine three attributes ...
649
point in this book the variables our code defined by assignment--aband --show up last in the dir result modules and namespaces module imports are way to run files of codebutas we'll expand on later in the bookmodules are also the largest program structure in python programsand one of the first key concepts in the langu...
650
use parentheses when you call reload (only)and you need to remember to use reload in the first place to get the current version of your code to run moreoverreloads aren' transitive--reloading module reloads that module onlynot any modules it may import--so you sometimes have to reload multiple files because of these co...
651
spam!spam!spam!spam!spam!spam!spam!spamthe exec call has an effect similar to an importbut it doesn' actually import the module --by defaulteach time you call exec this way it runs the file' code anewas though you had pasted it in at the place where exec is called because of thatexec does not require module reloads aft...
652
is usually referred to as an integrated development environment (ide)because it binds together various development tasks into single view in shortidle is desktop gui that lets you editrunbrowseand debug python programsall from single interface it runs portably on most python platformsincluding microsoft windowsx window...
653
on linux idle is also usually present as standard component today it might take the form of an idle executable or script in your pathtype this in shell to check on some machinesit may require an install (see appendix for pointers)and on others you may need to launch idle' top-level script from command line or icon clic...
654
windows use the file menu to begin (new windowor change (open source fileuse the text edit window' run menu to run the code in that window (run moduleyour file first if you've changed it since it was opened or last saved and forgot to save your changes-- common mistake when you're knee-deep in coding when run this wayt...
655
pressing enter to insert their text at the input promptor using standard cut-and-paste operationsthough these techniques tend to involve more steps (and can sometimes be triggered accidentallyoutside idleyou may be able to recall commands in an interactive session with the arrow keys on windows besides command history ...
656
idle is freeeasy to useportableand automatically available on most platforms generally recommend it to python newcomers because it simplifies some startup details and does not assume prior experience with system command lines howeverit is somewhat limited compared to more advanced commercial idesand may seem heavier th...
657
idle is python/tkinter programit can hang if you use it to run certain types of advanced python/tkinter programs this has become less of an issue in more recent versions of idle that run user code in one process and the idle gui itself in anotherbut some programs (especially those that use multithreadingmight still han...
658
that you use idle for this book' exercises if you're just starting outunless you are already familiar with and prefer command-line-based development mode there arehowevera handful of alternative ides for python developerssome of which are substantially more powerful and robust than idle apart from idlehere are some of ...
659
more will undoubtedly appear over time in factalmost every programmer-friendly text editor has some sort of support for python development these dayswhether it be preinstalled or fetched separately emacs and vimfor instancehave substantial python support ide choices are often subjectiveso encourage you to browse to fin...
660
pyrun_simplestring(" 'brave 'sir robin'")/this is cnot python /but it runs python code in this code snippeta program coded in the language embeds the python interpreter by linking in its librariesand passes it python assignment statement string to run programs may also gain access to python modules and objects and proc...
661
(for instancea web page might invoke script on server)howeverthese are beyond the scope of the present future possibilitiesthis reflects current practicebut much of the material is both platformand time-specific indeedmany of the execution and launch details presented arose during the shelf life of this book' various e...
662
code--but when you make mistake in python programyou get very useful and readable error message (you'll get to see some soonif you haven' alreadyif you already know pythonand especially for your own codethis is often enough --read the error messageand go fix the tagged line and file for manythis is debugging in python ...
663
tools in the open source domainincluding support for multithreaded programsembedded codeand process attachment the winpdb systemfor exampleis standalone debugger with advanced debugging support and cross-platform gui and console interfaces these options will become more important as we start writing larger scripts prob...
664
you can start an interactive session on windows and earlier by clicking your start buttonpicking the all programs optionclicking the python entryand selecting the "python (command line)menu option you can also achieve the same effect on windows and other platforms by typing python as system command line in your system'...
665
perform multithreading (an advanced technique beyond this book' scopealsoidle has some usability features that can burn you once you leave the idle guia script' variables are automatically imported to the interactive scope in idle and working directories are changed when you run filefor instancebut python itself does n...
666
code file in the original directoryor something similar in __pycache__ subdirectory there? scripts if your platform supports itadd the #line to the top of your module py module filegive the file executable privilegesand run it directly as an executable what does the first line need to contain#usually only has meaning o...
667
library and the structure of the documentation set it takes at least this long to become familiar with the locations of major topics in the manual setonce you've done thisit' easy to find what you need you can find this manual via the python start button entry on some windowsin the python docs option on the help pulldo...
668
types and operations
669
introducing python object types this begins our tour of the python language in an informal sensein python we do things with stuff "thingstake the form of operations like addition and concatenationand "stuffrefers to the objects on which we perform those operations in this part of the bookour focus is on that stuffand t...
670
this part' begin at the bottom--exploring both built-in objects and the expressions you can code to use them we'll move on to study statements in the next part of the bookthough we will find that they largely exist to manage the objects we'll meet here moreoverby the time we reach classes in the oop part of this bookwe...
671
are often built on top of built-in types such as lists and dictionaries for instancea stack data structure may be implemented as class that manages or customizes built-in list built-in objects are often more efficient than custom data structures python' built-in types employ already optimized data structure algorithms ...
672
object type example literals/creation numbers + decimal()fraction(strings 'spam'"bob' " ' \ ' 'sp\xc mlists [ [ 'three'] ]list(range( )dictionaries {'food''spam''taste''yum'}dict(hours= tuples ( 'spam' ' ')tuple('spam')namedtuple files open('eggs txt')open( ' :\ham bin''wb'sets set('abc'){' '' '' 'other core types bool...
673
you can perform only string operations on string and list operations on list in formal termsthis means that python is dynamically typeda model that keeps track of types for you automatically instead of requiring declaration codebut it is also strongly typeda constraint that means you can perform on an object only opera...
674
to string of digits with the built-in str functionand then getting the length of the resulting string with len the end result is the number of digits str and len work on many object typesmore on both as we move along on pythons prior to and once you start experimenting with floating-point numbersyou're likely to stumbl...
675
numberswe'll defer discussion of these types until later in this and book so farwe've been using python much like simple calculatorto do better justice to its built-in typeslet' move on to explore strings strings strings are used to record both textual information (your namefor instanceas well as arbitrary collections ...
676
operations are equivalent (though the first is easier to code and less easy to get wrong) [- 'ms[len( )- 'mthe last item in negative indexingthe hard way notice that we can use an arbitrary expression in the square bracketsnot just hardcoded number literal--anywhere that python expects valuewe can use literala variable...
677
concatenation 'spamxyzs is unchanged 'spams repetition 'spamspamspamspamspamspamspamspamnotice that the plus sign (+means different things for different objectsaddition for numbersand concatenation for strings this is general property of python that we'll call polymorphism later in the book--in sumthe meaning of an ope...
678
list of individual characters and join it back together with nothing betweenor use the newer bytearray type available in pythons and laters 'shrubberyl list(sl [' '' '' '' '' '' '' '' '' ' [ ' 'join( 'scrubberyexpand to listchange it in place join with empty delimiter bytes/list hybrid (ahead'bneeded in xnot [iord(cwor...
679
simple form of parsing)perform case conversionstest the content of the string (digitslettersand so on)and strip whitespace characters off the ends of the stringline 'aaa,bbb,ccccc,ddline split(','['aaa''bbb''ccccc''dd' 'spams upper('spams isalpha(true split on delimiter into list of substrings upperand lowercase conver...
680
the methods introduced in the prior section are representativebut smallsample of what is available for string objects in generalthis book is not exhaustive in its look at object methods for more detailsyou can always call the built-in dir function this function lists variables assigned in the caller' scope when called ...
681
as pydoc-- tool for extracting documentation from objects later in the bookyou'll see that pydoc can also render its reports in html format for display on web browser you can also ask for help on an entire string ( help( ))but you may get more or less help than you want to see--information about every string method in ...
682
cccccccccccccc ""msg '\naaaaaaaaaaaaa\nbbb\'\'\'bbbbbbbbbb""bbbbbbb\'bbbb\ncccccccccccccc\npython also supports raw string literal that turns off the backslash escape mechanism such literals start with the letter and are useful for strings like directory paths on windows ( ' :\text\new'unicode strings python' strings a...
683
'spam'spamencode('utf ' 'spam'spamencode('utf ' '\xff\xfes\ \ \ \ characters may be or bytes in memory encoded to bytes in utf- in files but encoded to bytes in utf- both and also support the bytearray string type we met earlierwhich is essentially bytes string ( str in xthat supports most of the list object' in-place ...
684
special codecs module handles unicode and represents content with the unicode type we'll meet unicode again in the files coverage later in this but save the rest of the unicode story for later in this book it crops up briefly in example in conjunction with currency symbolsbut for the most part is postponed until this b...
685
the python list object is the most general sequence provided by the language lists are positionally ordered collections of arbitrarily typed objectsand they have no fixed size they are also mutable--unlike stringslists can be modified in place by assignment to offsets as well as variety of list method calls accordingly...
686
pop method (or an equivalent del statementthen removes an item at given offsetcausing the list to shrink other list methods insert an item at an arbitrary position (insert)remove given item by value (remove)add multiple items at the end (extend)and so on because lists are mutablemost list methods also change the list o...
687
matrixas nested lists [ ]code can span lines if bracketed [ ] [[ ][ ][ ]herewe've coded list that contains three other lists the effect is to represent matrix of numbers such structure can be accessed in variety of waysm[ [ get row [ ][ get row then get item within the row the first operation here fetches the entire se...
688
[ add to each item in column [row[ for row in if row[ = filter out odd items [ the first operation herefor instanceadds to each item as it is collectedand the second uses an if clause to filter odd numbers out of the result using the modulus expression (remainder of divisionlist comprehensions make new lists of results...
689
next( next( run the iteration protocol next(the map built-in can do similar workby generating the results of running items through functionone at time and on request like rangewrapping it in list forces it to return all its values in python xthis isn' needed in where map makes list of results all at once insteadand is ...
690
when written as literalsdictionaries are coded in curly braces and consist of series of "keyvaluepairs dictionaries are useful anytime we need to associate set of values with keys--to describe the properties of somethingfor instance as an exampleconsider the following three-item dictionary (with keys "food,"quantity,an...
691
bob {'job''dev''name''bob''age' zipping notice how the left-to-right order of dictionary keys is scrambled mappings are not positionally orderedso unless you're luckythey'll come back in different order than you typed them the exact order may vary per pythonbut you shouldn' depend on itand shouldn' expect yours to matc...
692
pythonthis is all automatic--running the expression creates the entire nested object structure for us in factthis is one of the main benefits of scripting languages like python just as importantlyin lower-level language we would have to be careful to clean up all of the object' space when we no longer need it in python...
693
[' ' {' ' ' ' ' ' ' ' assigning new keys grows dictionaries [' 'error text omitted keyerror'freferencing nonexistent key is an error this is what we want--it' usually programming error to fetch something that isn' really there but in some generic programswe can' always know what keys will be present when we write our c...
694
the dictionaries we createthe get methoda conditional index with defaultthe python has_key methodan in work-alike that is no longer available in xthe try statementa tool we'll first meet in that catches and recovers from exceptions altogetherand the if/else ternary (three-partexpressionwhich is essentially an if statem...
695
dictionary keys automaticallyd {' ' ' ' ' ' for key in sorted( )print(key'=>' [key] = = = besides showcasing dictionariesthis use case serves to introduce the python for loop the for loop is simple and efficient way to step through all the items in sequence and run block of code for each item in turn user-defined loop ...
696
if the last section' for loop looks like the list comprehension expression introduced earlierit shouldboth are really general iteration tools in factboth will work on any iterable object that follows the iteration protocol--pervasive ideas in python that underlie all its iteration tools in nutshellan object is iterable...
697
about performance laterafter your program is workingand after you've proved that there is genuine performance concern more often than notyour code will be quick enough as it is if you do need to tweak code for performancethoughpython includes tools to help you outincluding the time and timeit modules for timing the spe...
698
and shrink because they are immutable (the parentheses enclosing tuple' items can usually be omittedas done here) 'spam' [ [ [ ][ append( attributeerror'tupleobject has no attribute 'appendwhy tuplessowhy have type that is like listbut supports fewer operationsfranklytuples are not generally used as often as lists in p...
699
text read(text 'hello\nworld\ ' (readis the default processing mode read entire file into string print(texthello world print interprets control characters text split(['hello''world'file content is always string other file object methods support additional features we don' have time to cover here for instancefile object...