id
int64
0
25.6k
text
stringlengths
0
4.59k
2,100
howeverout of range slice indexes are handled gracefully when used for slicingword[ : 'onword[ :'python strings cannot be changed -they are immutable thereforeassigning to an indexed position in the string results in an errorword[ 'jtypeerror'strobject does not support item assignment word[ :'pytypeerror'strobject does...
2,101
(continued from previous page squares[- :[ slicing returns new list all slice operations return new list containing the requested elements this means that the following slice returns new (shallowcopy of the listsquares[:[ lists also support operations like concatenationsquares [ [ unlike stringswhich are immutablelists...
2,102
[' '' '' ' [ [anx [[' '' '' '][ ] [ [' '' '' ' [ ][ ' first steps towards programming of coursewe can use python for more complicated tasks than adding two and two together for instancewe can write an initial sub-sequence of the fibonacci series as followsfibonacci seriesthe sum of two elements defines the next ab whil...
2,103
* print('the value of is'ithe value of is the keyword argument end can be used to avoid the newline after the outputor end the output with different stringab while print(aend=','ab ba+ , , , , , , , , , , , , , , , , first steps towards programming
2,104
an informal introduction to python
2,105
four more control flow tools besides the while statement just introducedpython knows the usual control flow statements known from other languageswith some twists if statements perhaps the most well-known statement type is the if statement for examplex int(input("please enter an integer")please enter an integer if print...
2,106
if you need to modify the sequence you are iterating over while inside the loop (for example to duplicate selected items)it is recommended that you first make copy iterating over sequence does not implicitly make copy the slice notation makes this especially convenientfor in words[:]loop over slice copy of the entire l...
2,107
print(range( )range( in many ways the object returned by range(behaves as if it is listbut in fact it isn' it is an object which returns the successive items of the desired sequence when you iterate over itbut it doesn' really make the listthus saving space we say such an object is iterablethat issuitable as target for...
2,108
(continued from previous pagefound number found an even number found number found an even number found number found an even number found number pass statements the pass statement does nothing it can be used when statement is required syntactically but the program requires no action for examplewhile truepass busy-wait f...
2,109
strings there are tools which use docstrings to automatically produce online or printed documentationor to let the user interactively browse through codeit' good practice to include docstrings in code that you writeso make habit of it the execution of function introduces new symbol table used for the local variables of...
2,110
expression)and methodname is the name of method that is defined by the object' type different types define different methods methods of different types may have the same name without causing ambiguity (it is possible to define your own object types and methodsusing classessee classesthe method append(shown in the examp...
2,111
def (al=[]) append(areturn print( ( )print( ( )print( ( )this will print [ [ [ if you don' want the default to be shared between subsequent callsyou can write the function like this insteaddef (al=none)if is nonel [ append(areturn keyword arguments functions can also be called using keyword arguments of the form kwarg=...
2,112
def function( )pass function( = traceback (most recent call last)file ""line in typeerrorfunction(got multiple values for keyword argument 'awhen final formal parameter of the form **name is presentit receives dictionary (see typesmappingcontaining all keyword arguments except for those corresponding to formal paramete...
2,113
the *args parameter are 'keyword-onlyargumentsmeaning that they can only be used as keywords rather than positional arguments def concat(*argssep="/")return sep join(argsconcat("earth""mars""venus"'earth/mars/venusconcat("earth""mars""venus"sep="'earth mars venusunpacking argument lists the reverse situation occurs whe...
2,114
pairs [( 'one')( 'two')( 'three')( 'four')pairs sort(key=lambda pairpair[ ]pairs [( 'four')( 'one')( 'three')( 'two')documentation strings here are some conventions about the content and formatting of documentation strings the first line should always be shortconcise summary of the object' purpose for brevityit should ...
2,115
(continued from previous pageprint("arguments:"hameggsreturn ham and eggs ('spam'annotations{'ham''return''eggs'argumentsspam eggs 'spam and eggs intermezzocoding style now that you are about to write longermore complex pieces of pythonit is good time to talk about coding style most languages can be written (or more co...
2,116
more control flow tools
2,117
five data structures this describes some things you've learned about already in more detailand adds some new things as well more on lists the list data type has some more methods here are all of the methods of list objectslist append(xadd an item to the end of the list equivalent to [len( ):[xlist extend(iterableextend...
2,118
list reverse(reverse the elements of the list in place list copy(return shallow copy of the list equivalent to [:an example that uses most of the list methodsfruits ['orange''apple''pear''banana''kiwi''apple''banana'fruits count('apple' fruits count('tangerine' fruits index('banana' fruits index('banana' find next bana...
2,119
using lists as queues it is also possible to use list as queuewhere the first element added is the first element retrieved ("first-infirst-out")howeverlists are not efficient for this purpose while appends and pops from the end of list are fastdoing inserts or pops from the beginning of list is slow (because all of the...
2,120
combs [for in [ , , ]for in [ , , ]if !ycombs append((xy)combs [( )( )( )( )( )( )( )note how the order of the for and if statements is the same in both these snippets if the expression is tuple ( the (xyin the previous example)it must be parenthesized vec [- - create new list with the values doubled [ * for in vec[- -...
2,121
(continued from previous page[ ]the following list comprehension will transpose rows and columns[[row[ifor row in matrixfor in range( )[[ ][ ][ ][ ]as we saw in the previous sectionthe nested listcomp is evaluated in the context of the for that follows itso this example is equivalent totransposed [for in range( )transp...
2,122
(continued from previous pagea [del can also be used to delete entire variablesdel referencing the name hereafter is an error (at least until another value is assigned to itwe'll find other uses for del later tuples and sequences we saw that lists and strings have many common propertiessuch as indexing and slicing oper...
2,123
(continued from previous page len(singleton singleton ('hello',the statement 'hello!is an example of tuple packingthe values and 'hello!are packed together in tuple the reverse operation is also possiblexyz this is calledappropriately enoughsequence unpacking and works for any sequence on the right-hand side sequence u...
2,124
dictionaries another useful data type built into python is the dictionary (see typesmappingdictionaries are sometimes found in other languages as "associative memoriesor "associative arraysunlike sequenceswhich are indexed by range of numbersdictionaries are indexed by keyswhich can be any immutable typestrings and num...
2,125
looping techniques when looping through dictionariesthe key and corresponding value can be retrieved at the same time using the items(method knights {'gallahad''the pure''robin''the brave'for kv in knights items()print(kvgallahad the pure robin the brave when looping through sequencethe position index and corresponding...
2,126
it is sometimes tempting to change list while you are looping over ithoweverit is often simpler and safer to create new list instead import math raw_data [ float('nan') float('nan') filtered_data [for value in raw_dataif not math isnan(value)filtered_data append(valuefiltered_data [ more on conditions the conditions us...
2,127
one lexicographical ordering for strings uses the unicode code point number to order individual characters some examples of comparisons between sequences of the same type( ( [ [ 'abc' 'pascal'python( ( ( ( - ( =( ( ('abc'' ') ( ('aa''ab')note that comparing objects of different types with is legal provided that the obj...
2,128
data structures
2,129
six modules if you quit from the python interpreter and enter it againthe definitions you have made (functions and variablesare lost thereforeif you want to write somewhat longer programyou are better off using text editor to prepare the input for the interpreter and running it with that file as input instead this is k...
2,130
(continued from previous page[ fibo __name__ 'fiboif you intend to use function often you can assign it to local namefib fibo fib fib( more on modules module can contain executable statements as well as function definitions these statements are intended to initialize the module they are executed only the first time the...
2,131
this is effectively importing the module in the same way that import fibo will dowith the only difference of it being available as fib it can also be used when utilising from with similar effectsfrom fibo import fib as fibonacci fibonacci( notefor efficiency reasonseach module is only imported once per interpreter sess...
2,132
search path after initializationpython programs can modify sys path the directory containing the script being run is placed at the beginning of the search pathahead of the standard library path this means that scripts in that directory will be loaded instead of modules of the same name in the library directory this is ...
2,133
(continued from previous pagesys ps 'ccprint('yuck!'yuckcthese two variables are only defined if the interpreter is in interactive mode the variable sys path is list of strings that determines the interpreter' search path for modules it is initialized to default path taken from the environment variable pythonpathor fro...
2,134
import builtins dir(builtins['arithmeticerror''assertionerror''attributeerror''baseexception''blockingioerror''brokenpipeerror''buffererror''byteswarning''childprocesserror''connectionabortederror''connectionerror''connectionrefusederror''connectionreseterror''deprecationwarning''eoferror''ellipsis''environmenterror''e...
2,135
(continued from previous pageaiffread py aiffwrite py auread py auwrite py effectssubpackage for sound effects __init__ py echo py surround py reverse py filterssubpackage for filters __init__ py equalizer py vocoder py karaoke py when importing the packagepython searches through the directories on sys path looking for...
2,136
in the previous item importing from package now what happens when the user writes from sound effects import *ideallyone would hope that this somehow goes out to the filesystemfinds which submodules are present in the packageand imports them all this could take long time and importing sub-modules might have unwanted sid...
2,137
from import echo from import formats from filters import equalizer note that relative imports are based on the name of the current module since the name of the main module is always "__main__"modules intended for use as the main module of python application must always use absolute imports packages in multiple director...
2,138
modules
2,139
seven input and output there are several ways to present the output of programdata can be printed in human-readable formor written to file for future use this will discuss some of the possibilities fancier output formatting so far we've encountered two ways of writing valuesexpression statements and the print(function ...
2,140
'helloworld str( 'helloworld repr( "'helloworld 'str( / ' 'the value of is repr( 'and is repr(yprint(sthe value of is and is the repr(of string adds string quotes and backslasheshello 'helloworld\nhellos repr(helloprint(hellos'helloworld\nthe argument to repr(may be any python objectrepr((xy('spam''eggs'))"( ('spam''eg...
2,141
the string format(method basic usage of the str format(method looks like thisprint('we are the {who say "{}!"format('knights''ni')we are the knights who say "ni!the brackets and characters within them (called format fieldsare replaced with the objects passed into the str format(method number in the brackets can be used...
2,142
(continued from previous page for complete overview of string formatting with str format()see formatstrings manual string formatting here' the same table of squares and cubesformatted manuallyfor in range( )print(repr(xrjust( )repr( *xrjust( )end='note use of 'endon previous line print(repr( * *xrjust( ) (note that the...
2,143
import math print('the value of pi is approximately % math pithe value of pi is approximately more information can be found in the old-string-formatting section reading and writing files open(returns file objectand is most commonly used with two argumentsopen(filenamemodef open('workfile'' 'the first argument is string...
2,144
to read file' contentscall read(size)which reads some quantity of data and returns it as string (in text modeor bytes object (in binary modesize is an optional numeric argument when size is omitted or negativethe entire contents of the file will be read and returnedit' your problem if the file is twice as large as your...
2,145
(continued from previous page seek( read( ' seek(- read( 'dgo to the th byte in the file go to the rd byte before the end in text files (those opened without in the mode string)only seeks relative to the beginning of the file are allowed (the exception being seeking to the very file end with seek( )and the only valid o...
2,146
contrary to json pickle is protocol which allows the serialization of arbitrarily complex python objects as suchit is specific to python and cannot be used to communicate with applications written in other languages it is also insecure by defaultdeserializing pickle data coming from an untrusted source can execute arbi...
2,147
eight errors and exceptions until now error messages haven' been more than mentionedbut if you have tried out the examples you have probably seen some there are (at leasttwo distinguishable kinds of errorssyntax errors and exceptions syntax errors syntax errorsalso known as parsing errorsare perhaps the most common kin...
2,148
the last line of the error message indicates what happened exceptions come in different typesand the type is printed as part of the messagethe types in the example are zerodivisionerrornameerror and typeerror the string printed as the exception type is the name of the built-in exception that occurred this is true for a...
2,149
(continued from previous pageclass ( )pass class ( )pass for cls in [bcd]tryraise cls(except dprint(" "except cprint(" "except bprint(" "note that if the except clauses were reversed (with except first)it would have printed bbb -the first matching except clause is triggered the last except clause may omit the exception...
2,150
instantiate an exception first before raising it and add any attributes to it as desired tryraise exception('spam''eggs'except exception as instprint(type(inst)the exception instance print(inst argsarguments stored in args print(inst__str__ allows args to be printed directlybut may be overridden in exception subclasses...
2,151
(continued from previous pageprint('an exception flew by!'raise an exception flew bytraceback (most recent call last)file ""line in nameerrorhithere user-defined exceptions programs may name their own exceptions by creating new exception class (see classes for more about python classesexceptions should typically be der...
2,152
defining clean-up actions the try statement has another optional clause which is intended to define clean-up actions that must be executed under all circumstances for exampletryraise keyboardinterrupt finallyprint('goodbyeworld!'goodbyeworldkeyboardinterrupt traceback (most recent call last)file ""line in finally claus...
2,153
for line in open("myfile txt")print(lineend=""the problem with this code is that it leaves the file open for an indeterminate amount of time after this part of the code has finished executing this is not an issue in simple scriptsbut can be problem for larger applications the with statement allows objects like files to...
2,154
errors and exceptions
2,155
nine classes classes provide means of bundling data and functionality together creating new class creates new type of objectallowing new instances of that type to be made each class instance can have attributes attached to it for maintaining its state class instances can also have methods (defined by its classfor modif...
2,156
understand what' going on incidentallyknowledge about this subject is useful for any advanced python programmer let' begin with some definitions namespace is mapping from names to objects most namespaces are currently implemented as python dictionariesbut that' normally not noticeable in any way (except for performance...
2,157
usuallythe local scope references the local names of the (textuallycurrent function outside functionsthe local scope references the same namespace as the global scopethe module' namespace class definitions place yet another namespace in the local scope it is important to realize that scopes are determined textuallythe ...
2,158
you can also see that there was no previous binding for spam before the global assignment first look at classes classes introduce little bit of new syntaxthree new object typesand some new semantics class definition syntax the simplest form of class definition looks like thisclass classnameclass definitionslike functio...
2,159
class instantiation uses function notation just pretend that the class object is parameterless function that returns new instance of the class for example (assuming the above class) myclass(creates new instance of the class and assigns this object to the local variable the instantiation operation ("callinga class objec...
2,160
method objects usuallya method is called right after it is boundx (in the myclass examplethis will return the string 'hello worldhoweverit is not necessary to call method right awayx is method objectand can be stored away and called at later time for examplexf while trueprint(xf()will continue to print hello world unti...
2,161
as discussed in word about names and objectsshared data can have possibly surprising effects with involving mutable objects such as lists and dictionaries for examplethe tricks list in the following code should not be used as class variable because just single list would be shared by all dog instancesclass dogtricks [m...
2,162
by stamping on their data attributes note that clients may add data attributes of their own to an instance object without affecting the validity of the methodsas long as name conflicts are avoided -againa naming convention can save lot of headaches here there is no shorthand for referencing data attributes (or other me...
2,163
inheritance of coursea language feature would not be worthy of the name "classwithout supporting inheritance the syntax for derived class definition looks like thisclass derivedclassname(baseclassname)the name baseclassname must be defined in scope containing the derived class definition in place of base class nameothe...
2,164
for most purposesin the simplest casesyou can think of the search for attributes inherited from parent class as depth-firstleft-to-rightnot searching twice in the same class where there is an overlap in the hierarchy thusif an attribute is not found in derivedclassnameit is searched for in base then (recursivelyin the ...
2,165
notice that code passed to exec(or eval(does not consider the classname of the invoking class to be the current classthis is similar to the effect of the global statementthe effect of which is likewise restricted to code that is byte-compiled together the same restriction applies to getattr()setattr(and delattr()as wel...
2,166
(continued from previous pagenext(it'anext(it'bnext(it'cnext(ittraceback (most recent call last)file ""line in next(itstopiteration having seen the mechanics behind the iterator protocolit is easy to add iterator behavior to your classes define an __iter__(method which returns an object with __next__(method if the clas...
2,167
for char in reverse('golf')print(charf anything that can be done with generators can also be done with class-based iterators as described in the previous section what makes generators so compact is that the __iter__(and __next__(methods are created automatically another key feature is that the local variables and execu...
2,168
classes
2,169
ten brief tour of the standard library operating system interface the os module provides dozens of functions for interacting with the operating systemimport os os getcwd(return the current working directory ' :\\python os chdir('/server/accesslogs'change current working directory os system('mkdir today'run the command ...
2,170
command line arguments common utility scripts often need to process command line arguments these arguments are stored in the sys module' argv attribute as list for instance the following output results from running python demo py one two three at the command lineimport sys print(sys argv['demo py''one''two''three'the g...
2,171
import random random choice(['apple''pear''banana']'applerandom sample(range( ) sampling without replacement [ random random(random float random randrange( random integer chosen from range( the statistics module calculates basic statistical properties (the meanmedianvarianceetc of numeric dataimport statistics data [ s...
2,172
tion for output formatting and manipulation the module also supports objects that are timezone aware dates are easily constructed and formatted from datetime import date now date today(now datetime date( now strftime("% -% -% % % % is % on the % day of % " dec is tuesday on the day of december dates support calendar ar...
2,173
quality control one approach for developing high quality software is to write tests for each function as it is developed and to run those tests frequently during the development process the doctest module provides tool for scanning module and validating tests embedded in program' docstrings test construction is as simp...
2,174
the sqlite module is wrapper for the sqlite database libraryproviding persistent database that can be updated and accessed using slightly nonstandard sql syntax internationalization is supported by number of modules including gettextlocaleand the codecs package brief tour of the standard library
2,175
eleven brief tour of the standard library -part ii this second tour covers more advanced modules that support professional programming needs these modules rarely occur in small scripts output formatting the reprlib module provides version of repr(customized for abbreviated displays of large or deeply nested containersi...
2,176
import locale locale setlocale(locale lc_all'english_united states ''english_united states conv locale localeconv(get mapping of conventions locale format("% "xgrouping=true' , , locale format_string("% * "(conv['currency_symbol']conv['frac_digits'] )grouping=true'$ , , templating the string module includes versatile t...
2,177
(continued from previous pageprint('{ --{ }format(filenamenewname)img_ jpg --ashley_ jpg img_ jpg --ashley_ jpg img_ jpg --ashley_ jpg another application for templating is separating program logic from the details of multiple output formats this makes it possible to substitute custom templates for xml filesplain text ...
2,178
(continued from previous pagedef run(self) zipfile zipfile(self outfile' 'zipfile zip_deflatedf write(self infilef close(print('finished background zip of:'self infilebackground asynczip('mydata txt''myarchive zip'background start(print('the main program continues to run in foreground 'background join(wait for the back...
2,179
weak references python does automatic memory management (reference counting for most objects and garbage collection to eliminate cyclesthe memory is freed shortly after the last reference to it has been eliminated this approach works fine for most applications but occasionally there is need to track objects only as lon...
2,180
from collections import deque deque(["task ""task ""task "] append("task "print("handling" popleft()handling task unsearched deque([starting_node]def breadth_first_search(unsearched)node unsearched popleft(for in gen_moves(node)if is_goal( )return unsearched append(min addition to alternative list implementationsthe li...
2,181
the decimal result keeps trailing zeroautomatically inferring four place significance from multiplicands with two place significance decimal reproduces mathematics as done by hand and avoids issues that can arise when binary floating point cannot exactly represent decimal quantities exact representation enables the dec...
2,182
brief tour of the standard library -part ii
2,183
twelve virtual environments and packages introduction python applications will often use packages and modules that don' come as part of the standard library applications will sometimes need specific version of librarybecause the application may require that particular bug has been fixed or the application may be writte...
2,184
(this script is written for the bash shell if you use the csh or fish shellsthere are alternate activate csh and activate fish scripts you should use instead activating the virtual environment will change your shell' prompt to show what virtual environment you're usingand modify the environment so that running python w...
2,185
(tutorial-envpip install --upgrade requests collecting requests installing collected packagesrequests found existing installationrequests uninstalling requests-successfully uninstalled requestssuccessfully installed requestspip uninstall followed by one or more package names will remove the packages from the virtual en...
2,186
pip has many more options consult the installing-index guide for complete documentation for pip when you've written package and want to make it available on the python package indexconsult the distributingindex guide virtual environments and packages
2,187
thirteen what nowreading this tutorial has probably reinforced your interest in using python -you should be eager to apply python to solving your real-world problems where should you go to learn morethis tutorial is part of python' documentation set some other documents in the set arelibrary-indexyou should browse thro...
2,188
before postingbe sure to check the list of frequently asked questions (also called the faqthe faq answers many of the questions that come up again and againand may already contain the solution for your problem what now
2,189
fourteen interactive input editing and history substitution some versions of the python interpreter support editing of the current input line and history substitutionsimilar to facilities found in the korn shell and the gnu bash shell this is implemented using the gnu readline librarywhich supports various styles of ed...
2,190
interactive input editing and history substitution
2,191
fifteen floating point arithmeticissues and limitations floating-point numbers are represented in computer hardware as base (binaryfractions for examplethe decimal fraction has value / / / and in the same way the binary fraction has value / / / these two fractions have identical valuesthe only real difference being tha...
2,192
that is more digits than most people find usefulso python keeps the number of digits manageable by displaying rounded value instead just remembereven though the printed result looks like the exact value of / the actual stored value is the nearest representable binary fraction interestinglythere are many different decim...
2,193
binary floating-point arithmetic holds many surprises like this the problem with " is explained in precise detail belowin the "representation errorsection see the perils of floating point for more complete account of other common surprises as that says near the end"there are no easy answers stilldon' be unduly wary of ...
2,194
representation error this section explains the " example in detailand shows how you can perform an exact analysis of cases like this yourself basic familiarity with binary floating-point representation is assumed representation error refers to the fact that some (mostactuallydecimal fractions cannot be represented exac...
2,195
meaning that the exact number stored in the computer is equal to the decimal value instead of displaying the full decimal valuemany languages (including older versions of python)round the result to significant digitsformat( '' the fractions and decimal modules make these calculations easyfrom decimal import decimal fro...
2,196
floating point arithmeticissues and limitations
2,197
sixteen appendix interactive mode error handling when an error occursthe interpreter prints an error message and stack trace in interactive modeit then returns to the primary promptwhen input came from fileit exits with nonzero exit status after printing the stack trace (exceptions handled by an except clause in try st...
2,198
to the name of file containing your start-up commands this is similar to the profile feature of the unix shells this file is only read in interactive sessionsnot when python reads commands from scriptand not when /dev/tty is given as the explicit source of commands (which otherwise behaves like an interactive sessionit...
2,199
glossary the default python prompt of the interactive shell often seen for code examples which can be executed interactively in the interpreter the default python prompt of the interactive shell when entering code for an indented code blockwhen within pair of matching left and right delimiters (parenthesessquare bracke...