id
int64
0
25.6k
text
stringlengths
0
4.59k
8,400
user input and error handling average rainfall (in mmin rome months between and jan feb mar apr may jun jul aug sep oct nov dec year although this data file is very smallit is fairly typical example oftenthere are one or more header lines with information that we are not really interested in processingand the remainder of the lines contain mix of text and numbers how can we read such filethe key to processing each line is to use split to separate the two words andfor instancestore them in two separate lists for later processingmonths [values [for line in infilewords line split(split into words months append(words[ ]values append(float(words[ ])these stepsinvolving for loop and then split to process each linewill be the fundamental recipe for all file processing throughout this book it is important to understand these steps properly and well worth spending some time reading small data files and playing around with split to become familiar with its use to write the complete program for reading the rainfall datawe must also account for the header line and the fact that the last line contains data of different type the complete code could look likedef extract_data(filename)infile open(filename' 'infile readline(skip the first line months [rainfall [for line in infilewords line split(#words[ ]monthwords[ ]rainfall months append(words[ ]rainfall append(float(words[ ])infile close(months months[:- drop the "yearentry annual_avg rainfall[- store the annual average rainfall rainfall[:- redefine to contain monthly data return monthsrainfallannual_avg monthsvaluesavg extract_data('rainfall txt'
8,401
print('the average rainfall for the months:'for monthvalue in zip(monthsvalues)print(monthvalueprint('the average rainfall for the year:'avgthis code is merely combination of tools and functions that we have already introduced above and in earlier so nothing is truly new notehoweverhow we skip the first line with single call to infile readline()which will simply read the first line and move to the next onethus being ready to read the lines in which we are interested if there are multiple header lines in the file we can simply add multiple readline calls to skip whatever we don' want to process notice also how list slicing is used to remove the yearly data from the lists negative indices in python lists run backwardstarting from the last elementso annual_avg rainfall[- will extract the last value in the rainfall list and assign it to annual_avg the list slicing months[:- ]rainfall[:- will extract all elements from the lists up tobut not including the last onethereby removing the yearly data from both lists writing data to files writing data to files follows the same pattern as reading we open file for writing and typically use for loop to traverse the datawhich we then write to the file using writeoutfile open(filename' ''wfor writing for data in somelistoutfile write(sometext '\ 'outfile close(notice the inclusion of \ in the call to write unlike printa call to write will not by default add line break after each call by defaulsso if we do not add this explicitlythe resulting file will consist of single long line it is often more convenient to have line-structured fileand for this we include the \nwhich adds line break the alternative way of opening files can also be used for writingand it ensures that the file is automatically closedwith open(filename' 'as outfile'wfor writing for data in somelistoutfile write(sometext '\ 'one should use caution when writing to files from python programs if you call open(filename,' 'with filename that does not exista new file will be createdhoweverif file with that name existsit will simply be deleted and replaced by an empty file thereforeeven if we do not actually write
8,402
user input and error handling any data to the filesimply opening it for reading will erase all its contents safer way to write to files is to use 'open(filename,' ')which will append data to the end of the file if it already existsand create new file if it does not exist for concrete exampleconsider the task of writing information from nested list to file we have following the nested list (rows and columns)data [ - - ] - - ][- - ][- - ]to write these data to file in tabular formwe follow the steps outlined above and use nested for loop (one for loop inside anotherto traverse the list and write the data the following code will do the trickwith open('tmp_table dat'' 'as outfilefor row in datafor column in rowoutfile write( '{column: }'outfile write('\ 'the resulting file looks like - - - - - - - - the nicely aligned columns are caused by the format specifier given to the fstring in the write call the code will work fine without the format specifierbut the columns will not be alignedand we also need to add space after every number orotherwiseeach line will just be long string of numbers that are difficult to separate the structure of the nested for loop is also worth stepping through in the code above the innermost loop traverses each rowwriting the numbers one by one to the file when this inner loop is done the program moves to the next line (outfile write('\ '))which writes linebreak to the file to end the line after this lineone pass of the outer for loop is finished and the program moves to the next iteration and the next line in the table the code for writing each number belongs inside the innermost loopwhereas the code for writing the line break is in the outer loopsince we only want one line break for each line handling errors in programs as demonstrated aboveallowing user input in our programs will often introduce errorsandas our programs grow in complexitythere can be multiple
8,403
other sources of errors as well python has general set of tools for handling such errors that is commonly referred to as exception handlingand it used in many different programming languages to illustrate how it workslet us return to the example with the atmospheric pressure formulaimport sys from math import exp sys argv[ float(hp print( exp(- / )as mentioned abovethis code can easily break if the user provides command line argument that cannot be converted to floatthat isany argument that is not pure number potentially even worse is our program failing with fairly cryptic error message if the user does not include command line argument at allas in the followingterminal terminalpython altitude_cml py traceback (most recent call last)file "altitude_cml py"line in sys argv[ indexerrorlist index out of range how can we fix such problems and make the program more robust with respect to user errorsone possible solution is to add an if-test to check if any command line arguments have been includedimport sys if len(sys argv print('you failed to provide command line arg !'exit(abort float(sys argv[ ] print( exp(- / )the function call exit(will simply abort the programso this extension solves part of the problem the program will still stop if it is used incorrectlybut it will provide more sensible and useful error messageterminal terminalpython altitude_cml py you failed to provide command line arg
8,404
user input and error handling howeverwe only handle one of the potential errorsand using if-tests to test for every possible error can lead to quite complex programs insteadit is common in python and many other languages to try to do what we intend to andif it failsto recover from the error this principle uses the try-except blockwhich has the following general structuretryexceptif something goes wrong in the try blockpython will raise an exception and the execution jumps to the except block inside the except blockwe need to add our own code for catching the exceptionbasically to detect what went wrong and try to fix it if no errors occur inside the try blockthe code inside the except block is not run and the program simply moves on to the first line after the try-except block improving the atmospheric pressure program with try-except to apply the try-except idea to the air pressure programwe can try to read from the command line and convert it to floatandif this failswe tell the user what went wrong and stop the programimport sys tryh float(sys argv[ ]exceptprint('you failed to provide command line arg !'exit( print( exp(- / )one could argue that this is not very different from the program using the if-testbut we shall see that the try-except block has some benefits firstwe can try to run this program with different inputwhich immediately reveals problemterminal terminalpython altitude_cml_except py you failed to provide command line arg terminalpython altitude_cml_except py you failed to provide command line arg regardless of what goes wrong inside our try blockpython will raise an exception that needs to be handled by the except block the problem with our code is that all possible errors will be handled the same way in the first casethe problem is that there are no argumentsthat issys argv[ does not existwhich leads to an indexerror this situation is correctly handled
8,405
by our code in the second casewe provide an argumentso the indexing of sys argv goes wellbut the conversion failssince python does not know how to convert the string to float this is different type of errorknown as valueerrorand we see that it is not treated very well by our except block we can improve the code by letting the except block test for different types of errorsand handling each one differentlyimport sys tryh float(sys argv[ ]except indexerrorprint('no command line argument for !'sys exit( abort execution except valueerrorprint( ' must be pure numbernot {sys argv[ ]}'exit( print( exp(- / )the following two examples illustrate how this more specific error handling worksterminal terminalpython altitude py no command line argument for hterminalpython altitude py the altitude must be pure numbernot " mof coursea drawback of this approach is that we need to guess in advance what could go wrong inside the try-blockand write code to handle all possible errors howeverwith some experiencethis is usually not very difficult python has many built-in error typesbut only few that are likely to occur and which need to be considered in the programs we encounter throughout this book in the code aboveif the try block would leads to different exception than what we catch in our except blockthe code will simply end with standard python error message if we want to avoid this behaviorand catch all possible exceptionswe could add generic except block such as exceptprint('something went wrong in reading input data!'exit(such block should be added after the except valueerror block in the code aboveand will catch any exception that is not an indexerror nor valueerror in this particular caseit can be difficult to imagine what kind of error that would bebut if it occursit will be caught and handled by our generic except block
8,406
user input and error handling the programmer can also raise exceptions in the code abovethe exceptions were raised by standard python functionsand we wrote the code to catch them instead of just letting python raise exceptionswe can raise our own and tailor the error messages to the problem at hand we provide two examples of such usecatching an exceptionbut raising new one (re-raisingwith an improved (tailorederror message raising an exception because of input data that we know are wrongalthough python accepts the data the basic syntax both for raising and re-raising an exception is raise exceptiontype(messagethe following code includes both examplesimport sys def read_altitude()tryh float(sys argv[ ]except indexerrorre-raisebut with specific explanationraise indexerror'the altitude must be supplied on the command line 'except valueerrorre-raisebut with specific explanationraise valueerrorf'altitude must be numbernot "{sys argv[ ]}' is read correctly as numberbut has wrong valueif raise valueerror( 'the formula is not valid for ={ }'return here we have defined function to handle the user inputbut the code is otherwise quite similar to the previous examples as abovethe except blocks will catch two different types of errorbutinstead of handling them ( stopping the program)the blocks here will equip the exceptions with more specific error messagesand then pass them on to be handled somewhere else in our program for this particular casethe difference is not very largeand one could argue that our first approach is simpler and therefore betterhoweverin larger programs it can often be better to re-raise exceptions and handle them elsewhere the last part of the function is differentsince the error raised here is not an error as far as python is concerned we can input any value of into our formulaandunless we input large negative numberit will not give rise to python error howeveras an estimate of air pressure the formula is only valid in the tropospherethe lower part of the earth' atmospherewhich extends from the lowest point on earth (on land)at if we set to be large negative numberthe argument for the exp function becomes large and positiveand leads to an overflowerror howeverthis error will occur only for values far outside the range of validity for our air pressure estimate
8,407
below sea levelto around km above sea level we can therefore let the program raise valueerror for any outside this rangeeven if it does not involve python error in the usual sense the following code shows how we can use the function aboveand how we can catch and print the error message provided with the exceptions the construction except as is used to access the error and use it inside the except blockas followstryh read_altitude(except (indexerrorvalueerroras eprint exception message and stop the program print(eexit(we can run the code in the terminal to confirm that we obtain the correct error messagesterminal terminalpython altitude_cml_except py the altitude must be supplied on the command line terminalpython altitude_cml_except py altitude must be numbernot terminalpython altitude_cml_except py the formula is not valid for = terminalpython altitude_cml_except py making modules so far in this course we have frequently used modules such as math and sysby importing them into our codefrom math import log log( call log function in math module import sys eval(sys argv[ ]access list argv in sys module modules are extremely useful in python programssince they contain collection of useful data and functions (as well as classes later)that we can reuse in our code but what if you have written some general and useful functions yourself that you would like to reuse in more than one programin such cases
8,408
user input and error handling it would be convenient to make your own module that you can import into other programs when needed fortunatelythis task is very simple in pythonjust collect the functions you want in fileand you have new moduleto look at specific examplesay we want create module containing the interest formula considered earlier and few other useful formulas for computing with interest rates we have the mathematical formulas ( / ) - ( / na ln ( ln( /  / - ( ( ( whereas abovep is the initial amountr is the interest rate (percent) is the number of yearsand is the final amount we now want to implement these formulas as python functions and make module of them we write the functions in the usual wayfrom math import log as ln def present_amount(prn)return *( / )** def initial_amount(arn)return *( / )**(-ndef years(par)return ln( / )/ln( / def annual_rate(pan)return *(( / )**( / if we now save these functions in file interest pyit becomes module that we can importjust as we are used to with built-in python modules as an examplesay we want to know how long it takes to double our money with an interest rate of the years function in the module provides the right formulaand we can import and use it in our programas followsfrom interest import years years( *ppprint( 'money has doubled after {nyears'we can add test block to module file if we try to run the module file above with python interest py from the terminalno output is produced since the functions are never called sometimes it can be useful to be able to add some examples of use in module fileto demonstrate how the functions
8,409
are called and used and give sensible output if we run the file with python interest py howeverif we add regular function callsprint statements and other code to the filethis code will also be run whenever we import the modulewhich is usually not what we want the solution is to add such example code in test block at the end of the module file the test block includes an if-test to check if the file is imported as module or if it is run as regular python program the code inside the test block is then executed only when the file is run as programand not when it is imported as module into another program the structure of the if-test and the test block is as followsif __name__ ='__main__'this test defines the test block the key is the first linewhich checks the value of the built-in variable __name__ this string variable is automatically created and is always defined when python runs (try putting print(__name__inside one of your programs or type it in an interactive session inside an imported module__name__ holds the name of the modulewhereas in the main program its value is "__main__for our specific casethe complete test block can look like if __name__ ='__main__' a_ present_amount(prnp_ initial_amount(arnn_ years(parr_ annual_rate(panprint( ' ={a_({ } ={p_({ } ={n_({ } ={r_({ })'test blocks are often included simply for demonstrating and documenting how modules are usedor they are included in files that we sometimes use as stand-alone programs and sometimes as modules as indicated by the namethey are also frequently used to test modules using what we learned about test functions in the previous we can do this by writing standard test function that tests the functions in the moduleand then simply calling this function from inside the test blockdef test_all_functions()define compatible values given three of thesecompute the remaining one and compare with the correct value (in parenthesisa_computed present_amount(prnp_computed initial_amount(arnn_computed years(parr_computed annual_rate(pandef float_eq(abtolerance= - )
8,410
user input and error handling """return true if = within the tolerance ""return abs( btolerance success float_eq(a_computedaand float_eq( _computeda and float_eq(p_computedpand float_eq(n_computednassert success could add message here if desired if __name__ ='__main__'test_all_functions(since we have followed the naming convention of test functionsthe function will be called if we runfor instancepytest interest pybut since we call it from inside the test blockthe test can also be run simply by python interest py in the latter casethe test will produce no output unless there are errors howeverif we import the module to use in another programthe test function is not runbecause the variable __name__ will be the name of the module ( interestand the test __name__ ='__main__will be evaluated as false how python finds our new module python has number of designated places where it looks for modules the first place it looks is in the same folder as the main programthereforeif we put our module files therethey will always be found howeverthis is not very convenient if we write more general modules that we plan to use from several other programs such modules can be put in designated directorysay /users/sundnes/lib/python/mymods or any other directory name that you choose then we need to tell python to look for modules in this directoryotherwiseit will not find the module on unix-like systems (linuxmacetc )the standard way to tell python where to look is by editing the environment variable called pythonpath environment variables are variables that hold important information used by the operating systemand pythonpath is used to specify the folders where python should look for modules if you type echo $pythonpath in the terminal windowyou will most likely obtain no outputsince you have not added any folder names to this variable we can put our new folder name in this variable by running the command terminal export pythonpath=/users/sundnes/lib/python/mymods howeverif the pythonpath already contained any foldersthese will now be lostthereforeto be on the safe sideit is better to use terminal export pythonpath=$pythonpath:/users/sundnes/lib/python/mymods this last command will simply add our new folder to the end of what is already in our pythonpath variable to avoid having to run this command
8,411
every time we want to import modulewe can put it in the file bashrcto ensure that it is run automatically when we open new terminal window the bashrc file should be in your home directory ( '/users/sundnesbashrc')and will be listed with ls - (the dot at the start of the filename makes it hidden fileso it will not show up with just ls if the file is not thereyou can simply create it in an editor and save it in your home directoryand the system should find it and read it automatically the next time you open terminal window as an alternative to editing the systemwide environment variablewe can also add our directory to the path from inside the program putting line such as this inside your codebefore you import the moduleshould allow python to find itsys path insert( '/users/sundnes/lib/python/mymods'as an alternative to creating your own directory for modulesand then tell python where to find themyou can place the modules in one of the places where python always looks for modules the location of these varies bit between different python installationsbut the directory itself is usually named site-packages if you have installed numpy or another package that is not part of the standard python distributionyou can locate the correct directory by importing this package for instancetype the following in an interactive python shellimport numpy numpy __file__ '/users/sundnes/anaconda /lib/python /site-packages/numpy/__init__ pythe last line reveals the location of the site-packages directoryand placing your own modules there will ensure python will find them numpy is package for numerical calculations it is not part of the standard python distributionbut it is often installed automatically if you install python from other sourcesfor instancefrom anaconda otherwiseit can be installed for instancewith pip or other tools the numpy package will be used extensively in the next
8,412
user input and error handling open access dieses kapitel wird unter der creative commons namensnennung international lizenz (in jeglichem medium und format erlaubtsofern sie den/die ursprunglichen autor(enund die quelle ordnungsgemass nenneneinen link zur creative commons lizenz beifugen und angebenob anderungen vorgenommen wurden die in diesem kapitel enthaltenen bilder und sonstiges drittmaterial unterliegen ebenfalls der genannten creative commons lizenzsofern sich aus der abbildungslegende nichts anderes ergibt sofern das betreffende material nicht unter der genannten creative commons lizenz steht und die betreffende handlung nicht nach gesetzlichen vorschriften erlaubt istist fur die oben aufgefuhrten weiterverwendungen des materials die einwilligung des jeweiligen rechteinhabers einzuholen
8,413
arrays and plotting in this we will learn to visualize mathematical functions and the results of mathematical calculations you have probably used variety of different plotting tools in the pastand we will now do much of the same thing in python the way standard plotting tools work in python is that we first compute number of points lying on the curve we want to show and then draw straight lines between them if we have enough pointsthe result looks like smooth curve for plotting mathematical functionsthis approach can seem bit primitivesince there are other tools we can use to simply type in mathematical expression and have the curve plotted on the screen howeverthe approach we use here is also much more flexiblesince we can plot data when there is no underlying mathematical functionfor instanceexperimental data read from file or results from numerical experiment to plot functions in pythonwe need to learn about the package matplotlibwhich is an extensive toolbox for plotting and visualization in additionit is useful to introduce the package named numpywhich is useful for storing storing arrays of data for efficient computations numpy and array computing the standard way to plot curve (xis to draw straight lines between points along the curveand for this purpose we need to store the coordinates of the points we could use lists for thisfor instancetwo lists and yand most of the plotting tools we will use work fine with lists howevera data structure known as an array is much more efficient than listand it offers number of nice features and advantages computing with arrays is often referred to as array computations or vectorized computationsand these concepts are useful for much more than just plotting curves arrays are generalizations of vectors in high school mathematicsvectors were introduced as line segments with directionrepresented by coor(cthe author( sundnesintroduction to scientific programming with pythonsimula springerbriefs on computing
8,414
arrays and plotting dinates (xyin the plane or (xyzin space this concept of vectors can be generalized to any number of dimensionsand we can view vector as general -tuple of numbersv ( vn- in pythonwe could use list to represent such vectorby storing component vi as element [iin the list howevervectors are so useful and common in scientific programming that special data structure has been created for themthe numpy array an array is much less flexible than listin that it has fixed length ( no append-method)and one array can only hold variables of the same type howeverarrays are also much more efficient to use in computationsand since they are designed for such usethey have number of useful features that can shorten and clarify our code for the purpose of plottingwe will mostly use one-dimensional arraysbut an array can have multiple indicessimilar to nested list for instancea two-dimensional array ai, can be viewed as table of numberswith one index for the row and one for the columnas followsa , , - - - - - am- , am- , - such two-dimensional case is similar to matrix in linear algebrabut numpy arrays do not follow the standard rules for mathematical operations on matrices the number of indices in an array is often referred to as the rank or the number of dimensions storing ( ,ypoints on curve in lists and arrays to make the array concept bit more concretewe consider the task mentioned abovewhere we want to store points on function curve (xall the plotting cases we will consider are based on this ideaso it makes sense to introduce it for simple example we have seen in previous that there are multiple ways to store such pairs of numbersfor instance in nested list containing (xypairs howeverfor the purpose of plottingthe easiest approach is to create two lists or arraysone holding the -values and another holding the -values the two lists/arrays should be of equal lengthand we will always create them using the same two steps firstwe create uniformly spaced -values that cover the interval where we want to plot the function thenwe run through these numbers and compute the corresponding -valuesstoring these in separate list or array the following interactive session illustrates the procedureusing list comprehensions to first create list of five -points on the interval [ ]and then compute the corresponding points (xfor (xx def ( )return ** dx /( - number of points spacing in [ ,
8,415
xlist [ *dx for in range( )ylist [ (xfor in xlistnow that we have the two liststhey can be sent directly to tool such as matplotlib for plottingbut before we do thiswe will introduce numpy arrays if we continue the interactive session from abovethe following lines will turn the two lists into numpy arraysimport numpy as np np array(xlisty np array(ylistmodule for arrays turn list xlist into array it is worth noting how we import numpy in the first line as alwayswe could import it with from numpy import *but this is bad habitsince numpy and math contain many functions with the same nameand we will often use both modules in the same program to ensure that we always know which module we are usingit is good habit to import numpy as we have done here using import numpy as np instead of simply import numpy saves us some typing in the rest of the code and is also more or less an accepted standard among python programmers converting lists to arrays using the array function from numpy is intuitive and flexiblebut numpy has number of built-in functions that are often more convenient to use two of the most widely used ones are called linspace and zeros the following interactive session is list-free version of the example abovewhere we create the numpy arrays directlyusing these two functionsimport numpy as np def ( )return ** np linspace( ny np zeros(nfor in range( ) [if( [ ]number of points points in [ zeros (float data typeas illustrated herewe will usually call linspace with three argumentswith the general form linspace(start,stop, )which will create an array of length ncontaining uniformly distributed values on the interval from start to stop if we leave out the third argumentas in linspace(start,stop) default value of = is used the start and stop arguments must always be provided an array of equally spaced -values is needed nearly every time we plot somethingso we will use linspace frequently it is worth spending time to become familiar with how it is used and what it returns the second numpy function used abovezeros( )does exactly what we would expectit creates an array of length containing only zeros we have seen earlier that common way to create list is to start with an empty list and fill it with values using for loop and the append-method we will
8,416
arrays and plotting often use similar approach to create an arraybut since an array has fixed length and no append-methodwe must first create an array of the right size and then loop over it with an index to fill in the values this operation is very commonso remembering the existence of numpy' zeros function is important as we have seen in lists in python are extremely flexibleand can contain any python object arrays are much more staticand we will typically use them for numbers ( type float or intthey can also be of other typessuch as boolean arrays (true/false)but single array always contains single object type we have also seen that arrays are of fixed length and do not have the convenient append-method sowhy do we use arrays at allone reasonwhich was mentioned aboveis that arrays are more efficient to store in memory and use in computations the other reason is that arrays can shortn our code and make it more readablesince we can perform operations on an entire array at once instead of using loops sayfor instancethat we want to compute the cosine of all the elements in list or array we know how to do this using for loop import numpy as np from math import cos np linspace( , , for in range(len( )) [icos( [ ]but if is an arrayy can be computed by np cos(xxarrayyarray in addition to being shorter and quicker to writethis code will run much faster than the code with the loop such computations are usually referred to as vectorized computationssince they work on the entire array (or vectorat once most of the standard functions we find in math have corresponding function in numpy that will work for arrays under the hood these numpy functions still contain for loopsince they need to traverse all the elements of the arraybut this loop is written in very efficient code and is therefore much faster than python loops we write ourselves function (xthat was written to work for single number will often work well for an array as well if the function uses only basic mathematical operators (+-*etc )we can pass it either number or an array as the argumentand it will work just fine with no modifications if the function uses more advanced operations that we need to importwe have to make sure to for the small array considered herecontaining just numbersthe efficiency gain does not matter at all it will be difficult to detect difference between the two versions even if we measure the run time of our program howevercertain numerical programs can use nested arrays containing tens of millions of numbersand in such cases the difference between loops and vectorized code becomes very noticeable
8,417
import these from numpy rather than mathsince the functions in math work only with single numbers the following example illustrates how it worksfrom numpy import sinexplinspace def ( )return ** + * - def ( )return sin( )*exp(- *xx (xfloat object is float linspace( intervals in [ , (xy is array (xz is array we see thatexcept for the initial import from numpythe two functions look exactly the same as if they were written to work on single number the result of the two function calls will be two arrays , of length with each element being the function value computed for the corresponding value of if we try to send an array of length to function imported from mathwe will obtain an error messageimport mathnumpy numpy linspace( array([ ]math cos( [ ] math cos(xtraceback (most recent call last)file ""line in typeerroronly size- arrays can be converted to python scalars numpy cos(xarray([ ]on the other handusing numpy functions on single numbers will work just fine natural question to askthenis why do we ever need to import from math at allwhy not use numpy functions all the timesince they do the job for both arrays and numbersthe answer is that we can certainly do thisand in most cases it will work finebut the functions in math are more optimized for single numbers (scalarsand are therefore faster one will rarely notice the differencebut there can be applications where the extra efficiency matters there are also functions in math ( factorialthat do not have corresponding version in numpy we started this by computing points along curve using lists and for loops now that we have introduced numpywe can solve this task much
8,418
arrays and plotting more easily by using arrays and array computations say we want to compute points on the curve described by the function (xe- sin( px) [ for [ pthe vectorized code can look as followsimport numpy as np np linspace( + np exp(- )*np sin( *np pi*xthis code is shorter and quicker to write than the one with lists and loopsmost people find it easier to read since it is closer to the mathematicsand it runs much faster than the list version we have already mentioned the term vectorized computationsand if you follow course in scientific python you will probably be asked at some point to vectorize function or computation this usually means nothing more than to ensure that all the mathematical functions are imported from numpy rather than mathand to then perform all the operations on entire arrays rather than looping over their individual elements the vectorized code should contain no for loops written in python the mathematical functions (xand (xin the example above are perfectly valid examples of vectorized functionseven though the actual functions look identical to the scalar versions the only major exceptions to this simple recipe for vectorization are functions that include if-tests for instancein we implemented piecewise-defined mathematical functions using if-tests these functions will not work if the input argument is an arraybecause test such as if has no precise meaning if is an array there are wayshoweverto solve this problemwhich we will look into later in the plotting curves with matplotlib the motivation for introducing numpy arrays was to plot mathematical functionsand now that we have introduced all the necessary tools we are finally ready to do so let us start with simple example say we want to plot the curve (xe- sin( px)for ranging from zero to four the code can look like import matplotlib pyplot as plt import numpy as np np linspace( + np exp(- )*np sin( *np pi*
8,419
plt plot(xyplt show(this code is identical to the example aboveexcept for the first line and the last two lines the first line imports the plotting tools from the matplotlib packagewhich is an extensive library of functions for scientific visualization we will only use small subset of the capabilities of matplotlibmostly from the module pyplotto plot curves and create animations of curves that change over time the next few lines are from the example aboveand they simply create the two arrays and defining the points along the curve the last two lines carry out the actual plottingthe call plt plot( ,yfirst creates the plot of the curveand then plt show(displays the plot on the screen the reason for keeping these separate is to make it easy to plot multiple curves in single plotby calling plot multiple times followed by single call to show the resulting plot is shown in figure common mistake is to forget the plt show(calland the program will then simply end without displaying anything on the screen fig simple plot of function using matplotlib the plot produced by the code above is very simple and contains no titleaxis labelsor other information we can easily add such information in the plot by using tools from matplotlibimport matplotlib pyplot as plt import numpy as np def ( )import and plotting
8,420
arrays and plotting return np exp(- )*np sin( *np pi*xn np linspace( + (xplt plot(xylabel='exp(- )*sin( $\pix)'plt xlabel(' 'label on the axis plt ylabel(' 'label on the axis plt legend(mark the curve plt axis([ - ][tmintmaxyminymaxplt title('my first matplotlib demo'plt savefig('fig pdf'plt savefig('fig png'plt show(make pdf image for reports make png image for web pages the plot resulting from this code is shown in figure most of the lines in the code should be self-explanatorybut some are worth comment the call to legend will create legend for the plotusing the information provided in the label argument passed to plt plot this is very useful when plotting multiple curves in single plot the axis function sets the length of the horizontal and vertical axes these are otherwise set automatically by matplotlibwhich usually works finebut in some cases the plot looks better if we set the axes manually later in this we will create animations of curves andin this casethe axes will have to be set to fixed lengths finallythe two calls to savefig will save our plot in two different file formatsautomatically determined by the file name provided if we plot multiple curves in single plotmatplotlib will choose the color of each curve automatically this default choice usually works wellbut we can control the look of each curve further if desired say we want to plot the functions - sin( pxand - sin( pxin the same plotimport matplotlib pyplot as plt import numpy as np def ( )return np exp(- )*np sin( *np pi*xdef ( )return np exp(- * )*np sin( *np pi*xx np linspace( (xy (xplt plot(xy ' --'label='exp(- )*sin( $\pix)'plt plot(xy ' :'label='exp(- * )*sin( $\pix)'plt xlabel(' 'plt ylabel(' '
8,421
fig example plot with more information added plt legend(plt title('plotting two curves in the same plot'plt savefig('fig_two_curves png'plt show(this example shows that the options for changing the color and plotting style of the curves are fairly intuitiveand can be easily explored by trial and error for full overview of all the optionswe refer the reader to the matplotlib documentation although the code example above was not too complexwe had to write an excess of lines just to plot two simple functions on the screen this level of programming is necessary if we want to produce professional-looking plotssuch as in presentationmaster' thesisor scientific report howeverif we just want quick plot on the screenthis can be achieved much more simply the following code lines will plot the same two curves as in the example aboveusing just three linest np linspace( plt plot( ,np exp(- )*np sin( *np pi* ), ,np exp(- * )*np sin( *np pi* )plt show(as alwaysthe effort we put in depends on what the resulting plot will be used forandin particularon whether we are just exploring some data on our own or plan on presenting it to others
8,422
arrays and plotting exampleplotting user-specified function say we want to write small program plotf py that asks the user to provide mathematical function ( )and then plots the curve (xwe can also ask the user to specify the boundaries of the curvethat isthe lower and upper limits for an example of running the program from the terminal can look like should be terminal terminalpython plot_input py write mathematical expression of : * ** - provide lower bound for : provide upper bound for : for these input values the program should plot the curve for [ the plot_input py program should work for any mathematical expression the task can be solved using the the functions input and eval introduced in from numpy import import matplotlib pyplot as plt formula input('write mathematical expression of :'xmin float(input('provide lower bound for :')xmax float(input('provide upper bound for :') linspace(xminxmax eval(formulaplt plot(xyplt show(this small program will stop and ask the user first for mathematical expression and then for the bounds on xand then it will proceed to plot the resulting curve note thatin this casewe have good reason to import numpy with from numpy import we want the user to be able type formula using standard mathematical terminologysuch as sin(xx** (rather than np sin(xx** for this to workwe need to import all the mathematical functions from numpy without prefix plotting discontinuous and piecewise-defined functions discontinuous functionsand functions defined in piecewise mannerare common in science and engineering we saw in how these could be implemented in python using if-testsbutas we briefly commented abovethis implementation gives rise to challenges when using arrays and numpy
8,423
to consider concrete examplesay we want to plot the heaviside functiondefined by ( > following the ideas from python implementation of this function could look like this def ( )if return elsereturn now we want to plot the function using the simple approach introduced above it is natural to simply create an array of values xand to pass this array to the function (xto compute the corresponding -valuesx linspace(- (xplot(xyfew points (simple curvehoweverif we try to run this codewe obtain an error messagea valueerror error inside the function ( )coming from the if line we can illustrate what goes wrong in an interactive python sessionx linspace(- , , array([- - ] array(truetruefalsefalsefalse]dtype=boolbool(bevaluate in boolean context valueerrorthe truth value of an array with more than one element is ambiguous use any(or all(we see here that the result of the statement is an array of boolean valueswhereasif were single numberthe result would be single boolean (true/falsethereforethe statement bool( )or tests such as if or if do not make sensesince it is impossible to say whether an array of multiple true/false values is true or false there are several ways to fix this problem one is to avoid the vectorization altogetherand return to the traditional for loop for computing the valuesimport numpy as np import matplotlib pyplot as plt np linspace(- + np zeros( + for in range(len( )) [ih( [ ]
8,424
arrays and plotting plt plot( ,yplt show( variation of the same approach is to alter the (xfunction itself and put the for loop inside itdef h_loop( ) np zeros(len( )or copy(for in range(len( )) [ih( [ ]return np linspace(- + h_loop(xwe see that this last approach ensures that we can call the function with an array argument xbut the downside to both versions is that we need to write quite lot of new codeand using for loop is much slower than using vectorized array computing an alternative approach is to use built-sin numpy function named vectorize which offers automatic vectorization of functions with if-tests the line hv np vectorize(hcreates vectorized version hv(xof the function (xthat will work with an array argument although this approach is obviously betterin the sense that the conversion is automatic so we need to write very little new codeit is about as slow as the two approaches using for loops third approach is to write new function where the if-test is coded differentlydef hv( )return np where( for this particular casethe numpy function where will evaluate the expression < for all elements in the array xand return an array of the same length as xwith values for all elements where < and for the others more generallya function with an if-test can be converted to an array-ready vectorized version in the following waydef ( ) it is fairly common misconception to believe that vectorizing computation or making vectorized version of functionalways involves using the function numpy vectorize this is not the case in most caseswe only need to make sure that we use array-ready functionssuch as numpy sinnumpy expetc instead of the scalar version from mathand code all calculations so that they work on an entire array instead of stepping through the elements with for loop the vectorize-function is usually only necessary for functions containing if-tests
8,425
if conditionx elsex return def f_vectorized( ) np where(conditionx return this conversion is notof courseas automatic as using vectorizeand requires writing some more codebut it is much more computationally efficient than the other versions efficiency is sometimes important when working with large arrays making movie of plot it is often useful to make animations or movies of plotsfor instance if the plot represents some physical phenomenon that changes with timeor if we want to visualize the effect of changing parameters matplotlib has multiple tools for creating such plotsand we will explore some of them here to start with specific caseconsider again the well-known gaussian bell function  - exp (xms the parameter is the location of the function' peakwhile is measure of the width of the bell curve plots of this function for different values of are shown in figure as an alternative illustration of how the parameters change the function we can make movie (animationof how (xmschanges shape as goes from two to movies are made from large set of individual plots movies of plots are created through the classical approach of cartoon movies (orreallyall movies)by creating set of images and viewing them in rapid sequence for our specific examplethe typical approach is to write for loop to step through the values and either show the resulting plots directly or store them in individual files for later processing regardless of the approachit is important to always fix the axes when making animations of plotsotherwisethe axis always adapts to the peak of the function and the visual impression is completely wrong we will look at three different ways to create movie of the kind outlined above
8,426
arrays and plotting = = = - - - fig the gaussian bell function plotted for different values of let the animation run livewithout saving any files with this approachthe plots are simply drawn on the screen as they are createdthat isone plot is shown for each pass of the for loop the approach is simplebut has the disadvantage that we cannot pause the movie or change its speed loop over all data valuescreate one plot for each value and save it to fileand then combine all the image files into movie this approach enables us to actually create movie file that can be played using standard movie player software the drawback of this approach is that it requires separately installed software ( imagemagickto create the movie and view the animation use funcanimation object from matplotlib this approach uses slightly more advanced feature of matplotliband can be considered combination of the two approaches above the animation is played livebut it can also be stored in movie file the downside is that the creation of the movie file still relies on externally installed software that needs to be installed separately and integrated with matplotlib first alternativerunning the movie live as the plots are created this approach is the simplest of the three and requires very few tools that we have not already seen we simply use for loop to loop over the valuescompute new -valuesand update the plot for each iteration of the loop howeverwe need to be aware of couple of technical details in particularthe intuitive approach of simply including calls to plot( ,yfollowed by show(inside the for loop does not work calling show(will make the program stop after the first plot is drawnand it will not run further until we close the plotting window additionallyrecall that we used multiple calls to
8,427
plot when we wanted multiple curves in single windowwhich is not what we want here insteadwe need to create an object that represents the plot and then update the -values of this object for each pass through the loop the complete code can look like import matplotlib pyplot as plt import numpy as np def (xms)return ( /(np sqrt( *np pi)* ))*np exp(- *(( - )/ )** s_start s_stop s_values np linspace(s_starts_stop np linspace( - *s_startm *s_start is max for = (smaller gives larger max valuemax_f (mms_stopy ( , ,s_stoplines plt plot( , #returns list of line objectsplt axis([ [ ] [- ]- max_f]plt xlabel(' 'plt ylabel(' 'for in s_valuesy (xmslines[ set_ydata( #update plot data and redraw plt draw(plt pause( most of the lines in this code should be familiarbut there are few items that are worth noting firstwe use the same plot function as earlierbut in slightly different manner generallythis function does two thingsit creates plot that is ready to display on the screen by subsequent call to show()and it returns special matplotlib object that represents the plot ( line objectin the examples abovewe did not need this objectso we did not care about itbut this time we store it in the variable lines note also that the plot-function always returns list of such objectsrepresenting all the curves of the plot in this casewe plot only one curveand the list has length one to update the plot inside the for loopwe call the set_ydata method of this objectthat islines[ set_ydata( )every time we have computed new array after updating the datawe call the function draw(to draw the curve on the screen the final line inside the for loop simply makes the program stop and wait for seconds if we remove this callthe movie runs too fast to be visibleand we can obviously adjust the speed by changing the function' argument as final comment on this coderemember the important message from abovethat we always need to fix the axes when creating moviesotherwisematplotlib will adjust the axes automatically for each plotand the resulting movie will not really look like movie at all
8,428
arrays and plotting herewe compute the maximum value that the function will obtain in the line max_f (mms_stop(based on either prior knowledge about the gaussian function or inspection of the mathematical expressionthis value is then used to set the axes for all the plots that make up the movie second alternativesaving image files for later processing this approach is very similar to the one abovebutinstead of showing the plots on the screenwe save them to filesusing the savefig function from matplotlib to avoid having each new plot over-write the previous filewe must include counter variable and formatted string to create unique filename for each iteration of the for loop the complete code is nearly identical to the one aboveimport matplotlib pyplot as plt import numpy as np def (xms)return ( /(np sqrt( *np pi)* ))*np exp(- *(( - )/ )** s_start s_stop s_values np linspace(s_starts_stop np linspace( - *s_startm *s_start is max for = (smaller gives larger max valuemax_f (mms_stopy ( , ,s_stoplines plt plot( ,yplt axis([ [ ] [- ]- max_f]plt xlabel(' 'plt ylabel(' 'frame_counter for in s_valuesy (xmslines[ set_ydata( #update plot data and redraw plt draw(plt savefig( 'tmp_{frame_counter: dpng'#unique filename frame_counter + running this program should create number of image filesall located in the directory in which we run the program converting these images into movie requires external softwarefor instanceconvert from the imagemagick software suite to make animated gifsor ffmpeg or avconv to make mp and other movie formats for instanceif we want to create an animated gif of the image files produced abovethe following command will do the trickterminal terminalconvert -delay tmp_png movie gif
8,429
the resulting gif can be played using animate from imagemagick or in browser note thatfor this approach to workone needs to be careful about the filenames the argument tmp_png passed to the convert function will simply replace with any textthereby sending all files with this pattern to convert the files are sent in lexicographic ( alphabeticalorderwhich is why we use the format specifier in the -string above it would be tempting so simply write {frame_counter}with no format specifierinside the -string to create the unique filenameand not worry about the format specifier this approach would create unique filenames such as tmp_ pngtmp_ pngand so on howeverwe would run into problems when creating the movie with convertsincefor instancetmp_ png comes before tmp_ png in the alphabetic ordering third alternativeusing built-in matplotlib tools the third approach is the most advanced and flexibleand it relies on built-in matplotlib tools instead of the explicit for loop that we used above without an explicit for loopthe actual steps of creating the animation are less obviousand the approach is therefore somewhat less intuitive the essential steps are the following make function to update the plot in our casethis function should compute the new array and call set_ydataas aboveto update the plot make list or array of the argument that changes (in this cases pass the function and the list as arguments to create funcanimation object after creating this objectwe can use various built-in methods to save the movie to fileshow it on the screenand so forth the complete code looks like the followingimport numpy as np import matplotlib pyplot as plt from matplotlib animation import funcanimation def (xms)return ( /(np sqrt( *np pi)* ))*np exp(- *(( - )/ )** s_start s_stop s_values np linspace(s_start,s_stop, np linspace(- *s_start, *s_start max_f ( , ,s_stopplt axis([ [ ], [- ], ,max_f]plt xlabel(' 'plt ylabel(' ' ( , ,s_start
8,430
arrays and plotting lines plt plot( , #initial plot to create the lines object def next_frame( ) (xmslines[ set_ydata(yreturn lines ani funcanimation(plt gcf()next_frameframes=s_valuesinterval= ani save('movie mp ',fps= plt show(most of the lines are identical to the examples abovebut there are some key differences we define function next_frame that contains all the code that updates the plot for each frameand returns an updated line object the argument to this function should be whatever argument that is changed for each frame (in our casesafter defining this functionwe use it to create funcanimation object in the next lineani funcanimation(plt gcf()next_frameframes=s_valuesinterval= this function call returns an object of type funcanimation the first argument is simply the current figure object we are working with (gcf being short for get current figure)the next is the function we just defined to update the framesthe third is the array of -values used to create the plotsand the last argument is the interval between frames in milliseconds numerous other optional arguments to the function can be used to tune the animation we refer to the matplotlib documentation for the details after the object is createdwe call the save method of the funcanimation class to create movie file, or the usual show(to play it directly on the screen more useful array operations at the start of this we introduced the most essential operations needed to use arrays in computations and for plottingbut numpy arrays can do much more here we introduce few additional operations that are convenient to know about when working with arrays firstwe often need to make an array of the same size as another array this can be done in several waysfor instanceusing the zeros function introduced aboveimport numpy as np np linspace( , , technicallywhat happens here is that we call the constructor of the class funcanimation to create an object of this class we will cover classes and constructors in detail in butfor nowit is sufficient to view this as regular function call that returns an object of type funcanimation this call relies on external software being installed and integrated with matplotlibso it might not work on all platforms
8,431
zeros( shapex dtypeor by copying the arraya copy(or by using the convenient function zeros_likea np zeros_like(xzeros and same size as if we write function that takes either list or an array as an argumentbut inside the function it needs to be an arraywe can ensure that it is converted by using the function asarraya asarray(athis statement will convert to an array if needed ( if is list or single number)but do nothing if is already an array the list slicing that we briefly introduced in also works for arraysand we can extract elements from an array using [ : :iherethe slice : : implies set of indices (fromtoincrement)exactly as for lists we can also use any list or array of integers to index into another arraya linspace( array( ] [[ , , ] array( ] [range( , , )- same as [ : : - array( - - ]finallywe can use an array of boolean expressions to pick out elements of an arrayas demonstrated in the following examplea [falsefalsetruefalsefalsetruefalsefalsea[ pick out all negative elements array([- - ] [ max(if [ ]< set [ ]= array( ]these indexing methods can often be quite usefulsincefor efficiencywe often want to avoid for loops over arrays elements many operations that are naturally implemented as for loops can be replaced by creative array slicing and indexingwith potentially substantial improvements in efficiency arrays can have any dimension just as listsarrays can have more than one index two-dimensional arrays are particularly relevantsince these are natural representations offor instancea table of numbers for instanceto represent set of numbers such as
8,432
arrays and plotting it is natural to use two-dimensional array ai, with the first index for the rows and the second for the columnst , , = am , am , in python codetwo-dimensional arrays are not much different from the onedimensional versionexcept for an extra index makingfillingand modifying two-dimensional array is done in much the same wayas illustrated by the following examplea zeros(( , ) [ , - [ , [ , [ , - [ , - table of numbers can also write (as for nested listsa[ ][ - notice the argument to the function zeroswhich is tuple specifying the number of rows and columns in the two-dimensional array we can create an array of any dimension we want by passing tuple of the correct length it is quite common for arrays used in numerical computations to be sparsethat isto have many zeros it is therefore often convenient to use zeros to create an array of the right size and then fill in the nonzero values alternativelywe could create nested list and convert it to an array with the array function used in the beginning of the open access dieses kapitel wird unter der creative commons namensnennung international lizenz (in jeglichem medium und format erlaubtsofern sie den/die ursprunglichen autor(enund die quelle ordnungsgemass nenneneinen link zur creative commons lizenz beifugen und angebenob anderungen vorgenommen wurden die in diesem kapitel enthaltenen bilder und sonstiges drittmaterial unterliegen ebenfalls der genannten creative commons lizenzsofern sich aus der abbildungslegende nichts anderes ergibt sofern das betreffende material nicht unter der genannten creative commons lizenz steht und die betreffende handlung nicht nach gesetzlichen vorschriften erlaubt istist fur die oben aufgefuhrten weiterverwendungen des materials die einwilligung des jeweiligen rechteinhabers einzuholen
8,433
dictionaries and strings in this we will mainly focus on two data typesdictionaries and strings dictionaries can be considered generalization of the list data typewhere the indices are not required to be integers we have already used strings multiple times in the previous but we will revisit them here to introduce number of new and useful functions both dictionaries and strings are particularly useful for reading and processing text filesand many of our examples will be related to such applications dictionaries in mathematicsa mapping is relation between objects or structures that often takes the form of function mapping is rule that assigns unique value (xto given input mappings are also widely used in computer science and can be implemented in many different ways for instancea python list can be viewed as mapping between integers (list indicesand the objects contained in list more general mappings can be implemented using functions and if-testsfor instancethe mapping 'norway--'oslo'sweden--'stockholm'france--'pariscould be implemented in python as functiondef ( )if ='norway'return 'osloelif ='sweden'return 'stockholmelif ='france'return 'paris(cthe author( sundnesintroduction to scientific programming with pythonsimula springerbriefs on computing
8,434
dictionaries and strings such an implementation is obviously not very convenient if we have large number of input and output valueshowever an alternative implementation of the mapping would be to use two lists of equal lengthwherefor instanceitem in list countries corresponds to item in list capitals howeversince such general mappings are useful in many contextspython provides special data structure for themcalled dictionary data structures similar to dictionary are used in many programming languagesbut they often have different names common names are associative arraysymbol tablehash mapor simply map dictionary can be seen as generalization of listwhere the indices are not required to be integersbut can be any immutable python data type the "indicesof dictionary are called keysand through this course we will mostly use strings as dictionary keys the dictionary implementation of the mapping above looks like {'norway':'oslo','sweden':'stockholm','france':'paris'and we can look up values in the dictionary just as we would in listusing the dictionary key instead of an indexprint( ['norway']to extend the dictionary with new valueswe can simply write ['germany'berlin notice this important difference between list and dictionary for list we had to use append(to add new elements dictionary has no append methodand to extend it we simply introduce new key and corresponding value dictionaries can be initialized in two different waysone is by using the curly bracketsas in the example above alternativelywe can use the built-in function dictwhich takes number of key-value pairs as arguments and returns the corresponding dictionary the two approaches can look like mydict {'key 'value 'key 'value temps {'oslo' 'london' 'paris' or mydict dict(key =value key =value temps dict(oslo= london= paris= notice the differences in syntaxparticularly the different use of quotation marks when initializing using curly bracketswe use colon to separate the key from its corresponding valueand the key can be any immutable python object ( strings in the example abovewhen using the dict functionwe pass the key-value pairs as keyword arguments to the functionand the keywords are converted to keys of type string howeverin both cases
8,435
the initialization involves defining set of key-value pairs to populate the dictionary dictionary is simply an unordered collection of such key-value pairs we are used to looping over lists to access the individual elements we can do the same with dictionarieswith the small but important difference that looping over dictionary means looping over its keysand not the values if we want to access the values we need to look them up in the dictionary using the keys for instancegeneric code to print all the values of dictionary would appear as followsfor key in dictionaryvalue dictionary[keyprint(valuea concrete example based on the example above could look like temps {'oslo' 'london' 'paris' 'madrid' for city in tempsprint( 'the {citytemperature is temps{city}'with the following outputthe paris temperature is the oslo temperature is the london temperature is the madrid temperature is as mentioned abovea dictionary is an unordered collection of key-value pairsmeaning that the sequence of the keys in the dictionary is arbitrary if we want to print or otherwise process the elements in particular orderthe keys first need to be sortedfor instanceusing the built-in function sortedfor city in sorted(temps)value temps[cityprint value alphabetic sort of keys there can be applications where sorting the keys in this manner is importantbut usually the order of dictionary is insignificant in most applications where the order of the elements is importanta list or an array is more convenient data type than dictionary dictionaries and lists share many similarities much of the functionality that we are familiar with for list also exists for dictionaries we canfor instancecheck if dictionary has particular key with the expression key in dictwhich returns true or falseif 'berlinin tempsprint('berlin:'temps['berlin']elseprint('no temperature data for berlin'no temperature data for berlin 'osloin temps standard boolean expression
8,436
dictionaries and strings true deleting an element of dictionary is done exactly the same way as with listsusing the operator deland we can use len to check its lengthdel temps['oslo'remove oslo key and value temps {'paris' 'london' 'madrid' len(tempsno of key-value pairs in dict in some casesit can be useful to access the keys or values of dictionary as separate entitiesand this can be accomplished with the methods keys and valuesfor instance temps keys(and temps values(for the case above these methods will return iteratorswhich are list-like objects that can be looped over or converted to listfor temp in temps values()print(temp keys_list list(temps keys()just as with listswhen we assign an existing dictionary to new variablethe dictionary is not copied insteadthe new variable name becomes reference to the same dictionaryand changing it will also change the original variable the following code illustrates the behaviort temps ['stockholm' change temps temps is also changed{'stockholm' 'paris' 'london' 'madrid' temps copy(take copy ['paris' ['paris' was not changed herethe call to temps copy(ensures that is copy of the original dictionaryand not referenceso changing it does not alter the original dictionary recall that lists behave in the same wayl [ [ [ copy(#for listsm [: [ [ also works
8,437
so far we have used texts (string objectsas keysbut the keys of dictionary can be any immutable (constantobject for instancewe can use integersfloatsand tuples as keysbut not lists since they are mutable objectsd { key is int { 'oslo' 'london'possible {( , ) ( ,- ) key is tuple {[ , ] [- , ] list is mutable/changeable typeerrorunhashable type'listof coursethe fact that these alternatives work in python does not mean that they are recommended or very useful it isfor instancehard to imagine useful application for dictionary with temperature as the key and city name as the value strings are the most obvious and common data type for dictionary keys and will also be the most common through this book howeverthere are applications where other types of keys can be usefulas we see in the following examples examplea dictionary for polynomials the information in polynomial such as ( - can be represented by dictionary with the power as the key (intand the coefficient as the value (float or int) { - more generallya polynomial written on the form (xn ci xi ii for some set of integers can be represented by dictionary with keys and values ci to evaluate polynomial represented by such dictionarywe need to iterate over the keys of the dictionaryextract the corresponding valuesand sum up the terms the following function takes two arguments dictionary poly and number or array and evaluates the polynomial in xdef eval_poly_dict(polyx)sum for power in polysum +poly[power]* **power
8,438
dictionaries and strings return sum we see that the function follows our standard recipe for evaluating sumset summation variable to zero and then add in all the terms using for loop we can write an even shorter version of the function using python' built-in function sumdef eval_poly_dict(polyx)python' sum can add elements of an iterator return sum(poly[power]* **power for power in polysince the keys of the polynomial dictionary are integerswe can also replace the dictionary with listwhere the list index corresponds to the power of the respective term the polynomial abovethat is- can be represented as the list [- and the general polynomial = ci is stored as [ cnthe function to evaluate polynomial represented by list is nearly identical to the function for the dictionary the function def eval_poly_list(polyx)sum for power in range(len(poly))sum +poly[power]* **power return sum will evaluate polynomial = ci for given an alternative and arguably more "pythonic versionuses the convenient enumerate functiondef eval_poly_list_enum(polyx)sum for powercoeff in enumerate(poly)sum +coeff* **power return sum the enumerate function essentially turns list into list of -tupleswhere the first element is the index of list element and the second is the element itself the function is quite convenient for iterating through list when we also need access to the indicesand it is very common in python programs the representations based on dictionaries and lists are very similarbut the list representation has the obvious disadvantage that we need to store all the zeros for "sparsehigh-order polynomialsthis can be quite inconvenientand the dictionary representation is obviously better the dictionary representation can also easily handle negative powersfor instance - {- print eval_poly_dict(px= this code will work just fine without any modifications of the eval_poly_dict function lists in python cannot have negative indices (since indexing list
8,439
with negative number implies counting indices from the end of the list)and extending the list representation to handle negative powers is not trivial task examplereading file data to dictionary say we have file deg txtcontaining temperature data for number of citiesoslolondonberlinparisromehelsinki we now want to read this file and store the information in dictionarywith the city names as keys and the temperatures as values the recipe is nearly identical to the one we previously used to read file data into listsfirst create an empty dictionary and then fill it with values read from the filewith open('deg txt'' 'as infiletemps {start with empty dict for line in infilecitytemp line split(city city[:- remove last char (:temps[cityfloat(tempthe only real difference between this code and previous examples based on lists is the way new data are added to the dictionary we used the append method to populate an empty listbut dictionaries have no such method insteadwe add new key-value pair with the line temps[cityfloat(tempapart from this technical differencethe recipe for populating dictionary is exactly the same as for lists string manipulation we have already worked with strings (having type str)in previous for instance introducing the very useful split-methods 'this is strings split(['this''is'' ''string'string manipulation is essential for reading and interpreting the content of filesand the way we process files often depends on the file structure for
8,440
dictionaries and strings instancewe need to know the line on which the relevant information startshow data items are separatedand how many data items are on each line the algorithm for reading and processing the text often needs to be tailored to the file structure although the split function already considered is quite flexibleand works for most of the examples presented in this bookit might not always be the best tool python has number of other ways to process stringswhich couldin some casesmake the text processing easier and more efficient to introduce some of the basic operations on stringswe can use the following string variable as an examples 'berlin at pmsuch string is really just sequence of charactersand it behaves much like other sequence data types such as lists and tuples for instancewe can index string to extract individual characterss[ 'bs[ 'es[- 'mslices also work in the way we are used to and can be used to extract substrings of strings 'berlin at pms[ :from index to the end of the string ' at pms[ : index and (not !' [ :- ' at ps[ :- ' citerating over string also works as we would expects 'berlin at pmfor s_ in sprint(s_end='strings have method named find that searches the string for given substringand returns the index of its locationas followss find('berlin' find('pm' find('oslo'- where does 'berlinstartat index not found
8,441
lists do not have find-methodbut they have method named indexwhich is quite similar in that it searches for given element in the list and returns its index strings also have method named index that does almost the same thing as find howeverwhile find will return - if the substring does not exist in the stringindex will end with an error message if we want to know if substring is part of string and do not really care about its locationwe can also use in'berlinin strue 'osloin sfalse if 'cin sprint ' foundelseprint 'no cc found this use of in to check for the existence of single element also works for lists and tuples for stringsthe method is slightly more flexiblesince we can check for substring of arbitrary length in many caseswe are interested not only in finding substringbut also in finding it and replace it with something else for this taskwe have string method named replace it takes two strings as argumentsand call such as replace( will replace by everywhere in the string the following examples illustrate how this method is useds 'berlin at pms replace(''__''berlin:__ __c__at__ __pms replace('berlin''bonn''bonn at pms replace( [: find(':')]'bonn''bonn at pmin the final examplewe combine find and replace to replace all the text before the ':with 'bonnfirsts find(':'returns the number sixwhich is the index where the ':is foundthen the slice [: is 'berlin'which is replaced by 'bonnhoweverone important observation in this example is that these repeated calls to replace do not change sbutinsteadeach call returns new string where the substrings have been replaced as requested splitting and joining strings we have already introduced the split methodwhich is arguably the most useful method for reading and processing text files as we recall from the call split(sepwill split the string into list of substrings separated by sep the sep argument is optionaland if it is omitted the string is split with respect to whitespace consider these two simple examples to recall how split is used
8,442
dictionaries and strings 'berlin at pms split(':'['berlin' at pm' split(['berlin:'' '' ''at'' ''pm'the split method has an inversecalled joinwhich is used to put list of strings together with delimiter in betweenstrings ['newton''secant''bisection''join(strings'newtonsecantbisectionnotice that we call the join method belonging to the delimiter ''which is string objectand pass the list of strings as an argument if we want to put the same list together separated by whitespacewe would simply replace 'join(stringsin the example above with join(stringssince split and join are inverse operationsusing them in sequence will give back the original stringas in the following examplel 'oslo at pmwords split( join(wordsl = true common use case for the join method is to split off known number of words on line say we want to read file in the following formatand combine the city name and the country into single stringtromso norway molde norway oslo norway stockholm sweden uppsala sweden the following code will read such file and create nested dictionary containing the data cities {with open('cities txt'as infilefor line in infilewords line split(name 'join(words[: ]data {'lat'float(words[ ])data['pop'int(words[ ]cities[namedata 'long':float(words[ ])here the line name 'join(words[: ]will create strings such as 'tromsonorway'which are then used as dictionary (keysthe value associated with each key is dictionary containing the latitude and longitude data in most of the examples considered so far we have mostly used split for processing text files line by linebut in some cases we have string with
8,443
great deal of text on multiple lines and we want to split it into single lines we can do so by using the split method with the appropriate separator for instanceon linux and mac systemssthe line separator is \nt ' st line\ nd line\ rd lineprint st line nd line rd line split('\ '[' st line'' nd line'' rd line'this example works fine on mac or linuxbut the line separator on windows is not \nbut \ \nandfor platform-independent solutionit is better to use the method splitlines()which works with both line separatorst ' st line\ nd line\ rd line#unix format splitlines([' st line'' nd line'' rd line' ' st line\ \ nd line\ \ rd linewindows splitlines(cross platform[' st line'' nd line'' rd line'strings are constant immutable objects in many of the examples abovewe highlighted the similarity between strings and listssince we are very familiar with lists from earlier howeverstrings are even more similar to tuplessince they are immutable objects we could change the elements of list in place by indexing into the listbut this does not work for strings trying to assign new value to part of string will result in an error messages[ typeerror'strobject does not support item assignment insteadto perform such replacementwe can build new string manually by adding pieces of the original string or use the replace method introduced abovebuild new string by adding pieces of ss [: ' [ : 'berlin at pms replace( [ ], 'berlin at pmthe fact that strings are immutablebut still have method such as replacecould be confusing to some how can we replace substring with another if strings are immutable objectsthe answer is that replace does not really change the original stringbut returns new one this behavior is similar tofor instancethe call split()which will not turn into list but
8,444
dictionaries and strings insteadwill leave unchanged and return list of the substrings similarlya call such as replace( , does not change but it will return new string that we can assign to either or some other variable nameas we did in the example above the call replace( , does nothing useful on its ownunless it is combined into an assignment such as replace( , or replace( , other convenient string methods in python it is often convenient to strip leading or trailing whitespace from stringand there are methods strip()lstrip(and rstrip(to do just thiss text with leading/trailing space strip('text with leading/trailing spaces lstrip(left strip 'text with leading/trailing space \ns rstrip(right strip text with leading/trailing space\nwe can also check whether string contains only numbers (digits)only spaceor if string starts or ends with given substring' isdigit(true isdigit(false ' isdigit(false isspace(true \nisspace(true \ isspace(true 'isspace(false blanks newline tab empty string startswith('berlin'true endswith('am'false finallywe might be interested in converting between lowercase and uppercase characterss lower('berlin at pms upper('berlin at pmthe examples shown so far are just few of the useful string operations defined in python many more existbut all the text processing tasks considered
8,445
in this book can be accomplished with the operations listed here nearly all the tasks we encounter in this book can be solved by using combination of split and join in addition to string indexing and slicing examplereading pairs of numbers ( ,yfrom file to summarize some string operations using an exampleconsider the task of reading files in the following format( , ( , ( ,- (- , ( ,- ( , ( , ( ,- ( ,- we want to read these coordinate pairsconvert the numbers to floatsand store them as list of tuples the algorithm is similar to the way we processed files earlier read the file line by line for each linesplit the line into words (each number pair for each wordstrip the parentheses and split the rest with respect to comma to extract the numbers from these operationswe can observe that the split function is probably good toolas it usually is when processing text files to strip the parentheses from the coordinate pairswe canfor instanceuse slicing translated into codethe example can look as followspairs [list of ( pairs of numbers with open('pairs txt'' 'as linesfor line in lineswords line split(for word in wordsword word[ :- strip off parentheses word split(',' float( ) float( pair ( pairs append(pairthere are multiple alternative solutions for reading file in the given formatbut this one is quite simple and also relatively robust with respect to handling different numbers of pairs on each line and variable use of whitespace
8,446
dictionaries and strings open access dieses kapitel wird unter der creative commons namensnennung international lizenz (in jeglichem medium und format erlaubtsofern sie den/die ursprunglichen autor(enund die quelle ordnungsgemass nenneneinen link zur creative commons lizenz beifugen und angebenob anderungen vorgenommen wurden die in diesem kapitel enthaltenen bilder und sonstiges drittmaterial unterliegen ebenfalls der genannten creative commons lizenzsofern sich aus der abbildungslegende nichts anderes ergibt sofern das betreffende material nicht unter der genannten creative commons lizenz steht und die betreffende handlung nicht nach gesetzlichen vorschriften erlaubt istist fur die oben aufgefuhrten weiterverwendungen des materials die einwilligung des jeweiligen rechteinhabers einzuholen
8,447
classes in this we introduce classeswhich is fundamental concept in programming most modern programming languages support classes or similar conceptsand we have already encountered classes earlier in this book recallfor instancefrom how we can check the type of variable with the type functionand the output will be of the form and so on this simply states that the type of an object is defined in the form of class every time we createfor instancean integer variable in our programwe create an object or instance of the int class the class defines how the objects behave and what methods they contain we have used large number of different methods bound to objectssuch as the append method for list objects and split for strings all such methods are part of the definition of the class to which the object belongs so farwe have only used python' built-in classes to create objectsbut in this we will write our own classes and use them to create objects tailored to our particular needs basics of classes class packs together data and functions in single unit as seen in previous functions that are bound to class or an object are usually called methodsand we will stick to this notation in the present classes have some similarity with moduleswhich are also collections of variables and functions that naturally belong together howeverwhile there can be only single instance of modulewe can create multiple instances of class different instances of the same class can contain different databut they all behave in the same way and have the same methods think of basic python class such as intwe can create many integer variables in programand they obviously have different values (data)but we know that they all have the same general behavior and the same set of operations defined for them (cthe author( sundnesintroduction to scientific programming with pythonsimula springerbriefs on computing
8,448
classes the same goes for more complex python classes such as lists and stringsdifferent objects contain different databut they all have the same methods the classes we create in this behave in exactly the same way first examplea class representing function to start with familiar examplewe return to the formula calculating atmospheric pressure as function of altitude the formula we used is simplification of more general barometric formulagiven byp - gh/rt ( where is the molar mass of airg is the gravitational constantr is the gas constantt is temperatureand is the pressure at sea level we obtain the simpler formula used earlier by defining the scale height as rt / it could be interesting to evaluate ( for different temperatures andfor each value of to create table or plot of how the pressure varies with altitude for each value of we need to call the function many timeswith different values of how should we implement this in convenient wayone possible solution would be to have both and as argumentsfrom math import exp def barometric(ht) # /( *sr # /( *molm #kg/mol #kpa return exp(- * * /( * )this solution obviously worksbut if we want to call the function many times for the same value of then we still need to pass it as an argument every time it is called howeverwhat if the function is to be passed as an argument to another function that expects it to take single argument only? in this caseour function with two arguments will not work partial solution would be to include default value for the argumentbut we would still have problem if we want different value of another solution would be to have as the only argumentand as global variablet def barometric( ) # /( * this situation is quite common in python programs considerfor instancethe implementation of newton' method in in the functions newton and newton these functions expect two functions as arguments ( and dfdx)and both are expected to take single argument (xpassing in function that requires two or more arguments will lead to an error
8,449
# /( *mol#kg/mol #kpa return exp(- * * /( * )we now have function that takes single argumentbut defining as global variable is not very convenient if we want to evaluate (tfor different values of we could also set as local variable inside the function and define different functions barometric ( )barometric ( )etc for different values of tbut this is obviously inconvenient if we want many values of howeverwe shall see that programming with classes and objects offers exactly what we needa convenient solution to create family of similar functions that all have their own value of as mentioned abovethe idea of class is to pack together data and methods (or functionsthat naturally operate on the data we can make class barometric for the formula at handwith the variables rt,' 'gand as dataand method value(tfor evaluating the formula all classes should also have method named __init__ to initialize the variables the following code defines our function class class barometricdef __init__(selft)self self self self self # # /( * # /( *mol#kg/mol #kpa def value(selfh)return self exp(-self *self * /(self *self )having defined this classwe can create instances of the class with specific values of the parameter tand then we can call the method value with as the only argumentb barometric( = value( barometric( = value( create instance (objectcompute function value these code segments introduce number of new concepts worth dissecting firstwe have class definition thatin pythonalways starts with the word classfollowed by the name of the class and colon the following indented block of code defines the contents of the class just as we are used to when we implement functionsthe indentation defines what belongs inside the class definition the first contents of our classand of most classesis method with the special name __init__which is called the constructor of the class this method is automatically called every time we create an instance in the classas in the line barometric( = above inside the methodwe
8,450
classes define all the constants used in the formula self tself gand so on where the prefix self means that these variables become bound to the object created such bound variables are called attributes finallywe define the method valuewhich evaluates the formula using the predefined and objectbound parameters self tself gself rself mand self after we have defined the classevery time we write line such as barometric( = we create new variable (instanceb of type barometric the line looks like regular function callbutsince barometric is the definition of class and not functionbarometric( = is instead call to the classconstructor the constructor creates and returns an instance of the class with the specified values of the parametersand we assign this instance to the variable all the __init__ functions we encounter in this book will follow exactly the same recipe their purpose is to define number of attributes for the classand they will typically contain one or more lines of the form self awhere is either an argument passed to the constructor or value defined inside it as always in programmingthere are different ways to achieve the same thingand we could have chosen different implementation of the class above since the only argument to the constructor is tthe other attributes never change and they could have been local variables inside the value methodclass barometric def __init__(selft)self # def value(selfh) return exp(- * * /( *self )notice thatinside the value methodwe only use the self prefix for tsince this is the only variable that is class attribute in this version of the class the other variables are regular local variables defined inside the method this class does exactly the same thing as the one defined aboveand one could argue that this implementation is bettersince it is shorter and simpler than the one above howeverdefining all the physical constants in one place (in the constructorcan make the code easier to readand the class easier to extend with more methods as third possible implementationwe could move some of the calculations from the value method to the constructorclass barometric def __init__(selft) # /( *sr # /( *molm #kg/mol self * /( *gself #kpa
8,451
def value(selfh)return self exp(- /self in this classwe use the definition of the scale height from above and compute and store this value as an attribute inside the constructor the attribute self is then used inside the value method notice that the constants grand arein this caselocal variables in the constructorand neither these nor are stored as attributes they are only accessible inside the constructorwhile self and self are stored and can be accessed later from within other methods at this pointmany will be confused by the self variableand the fact thatwhen we define the methods __init__ and value they take two argumentsbutwhen calling themthey take only one the explanation for this behavior is that self represents the object itselfand it is automatically passed as the first argument when we call method bound to the object when we write value( it is equivalent to the call barometric value( , here we explicitly call the value method that belongs to the barometric class and pass the instance as the first argument inside the methodb then becomes the local variable selfas is usual when passing arguments to functionand we can access its attributes tgand so on exactly the same thing happens when we call value( )but now the object is automatically passed as the first argument to the method it looks as if we are calling the method with single argumentbut in reality it gets two the use of the self variable in python classes has been the subject of many discussions even experienced programmers find it confusingand many have questioned why the language was designed this way there are some obvious advantages to the approachfor instanceit very clearly distinguishes between instance attributes (prefixed with selfand local variables defined inside method howeverif one is struggling to see the reasoning behind the self variableit is sufficient to remember the following two rules(iself is always the first argument in method definitionbut is never inserted when the method is calledand (iito access an attribute inside methodthe attribute needs to be prefixed with self an advantage of creating class for our barometric function is that we can now send value as an argument to any other function that expects function argument that takes single argument considerfor instancethe following small examplewhere the function make_table prints table of the function values for any function passed to itfrom math import sinexppi
8,452
classes from numpy import linspace def make_table(ftstopn)for in linspace( tstopn)print(tf( )def ( )return sin( )*exp(-tmake_table( *pi send ordinary function barometric( make_table( value *pi send class method because of how (tis used inside the functionwe need to send make_table function that takes single argument our value method satisfies this requirementbut we can still use different values of by creating multiple instances more general python classes of coursepython classes have far more general applicability than just the representation of mathematical functions general python class definition follows the recipe outlined in the example aboveas followsclass myclassdef __init__(selfp )self attr self attr def method (selfarg)#access attributes with self prefix result self attr #create new attributes if desired self attrx arg return result def method (self)printwe can define as many methods as we want inside the classwith or without arguments when we create an instance of the class the methods become bound to the instanceand are accessed with the prefixfor instancem method (if is an instance of myclass it is common to have constructor where attributes are initializedbut this is not requirement attributes can be defined whenever desiredfor instanceinside methodas in the line self attrx arg in the example aboveor even from outside the classm myclass( , new_attr
8,453
the second line here creates new attribute new_attr for the instance of myclass such addition of attributes is entirely validbut it is rarely good programming practice since we can end up with instances of the same class having different attributes it is good habit to always equip class with constructor and to primarily define attributes inside the constructor protected class attributes for more classical computer science example of python classlet us look at class representing bank account natural attributes for such class will be the name of the ownerthe account numberand the balanceand we can include methods for depositswithdrawalsand printing information about the account the code for defining such class could look like thisclass bankaccountdef __init__(selffirst_namelast_namenumberbalance)self first_name first_name self last_name last_name self number number self balance balance def deposit(selfamount)self balance +amount def withdraw(selfamount)self balance -amount def print_info(self)first self first_namelast self last_name number self numberbal self balance '{first{last}{number}balance{balance}print(stypical use of the class could be something like the followingwhere we create two different account instances and call the various methods for depositswithdrawalsand printing informationa account('john''olsson'' ' account('liz''olsson'' ' deposit( withdraw( withdraw( withdraw( print " ' balance:" balance ' balance print_info(john olsson balance print_info(
8,454
classes liz olsson balance howeverthere is nothing to prevent user from changing the attributes of the account directlya first_name 'some other namea balance number ' although it can be tempting to adjust bank account balance when neededit is not the intended use of the class directly manipulating attributes in this way will very often lead to errors in large software systemsand is considered bad programming style insteadattributes should always be changed by calling methodsin this casewithdraw and deposit many programming languages have constructions that can limit the access to attributes from outside the classso that any attempt to access them will lead to an error message when compiling or running the code python has no technical way to limit attribute accessbut it is common to mark attributes as protected by prefixing the name with an underscore ( _namethis convention tells other programmers that given attribute or method is not supposed to be accessed from outside the classeven though it is still technically possible to do so an account class with protected attributes can look like the followingclass bankaccountpdef __init__(selffirst_namelast_namenumberbalance)self _first_name first_name self _last_name name self _number number self _balance balance def deposit(selfamount)self _balance +amount def withdraw(selfamount)self _balance -amount def get_balance(self)return self _balance new read balance value def print_info(self)first self first_namelast self last_name number self numberbal self balance '{first{last}{number}balance{balance}print(swhen using this classit will still be technically possible to access the attributes directlyas in bankaccountp('john''olsson'' ' _number ' howeverall experienced python programmers will know that the second line is serious violation of good coding practice and will look for better
8,455
way to solve the task when using code libraries developed by otherssuch conventions are risky to breaksince internal data structures can changewhile the interface to the class is more static the convention of protected variables is how programmers tell users of the class what can change and what is static library developers can decide to change the internal data structure of classbut users of the class might not even notice this change if the methods to access the data remain unchanged since the class interface is unchangedusers who followed the convention will be finebut users who have accessed protected attributes directly could be in for surprise special methods in the examples abovewe define constructor for each classidentified by its special name __init__this name is recognized by pythonand the method is automatically called every time we create new instance of the class the constructor belongs to family of methods known as special methodswhich are all recognized by double leading and trailing underscores in the name the term special methods could be bit misleadingsince the methods themselves are not really special the special thing about them is the namewhich ensures that they are automatically called in different situationssuch as the __init__ function being called when class instances are created there are many more such special methods that we can use to create object types with very useful properties considerfor instancethe first example of this where the class barometric contained the method value(hto evaluate mathematical function after creating an instance named barowe could call the method with baro value(thoweverit would be even more convenient if we could just write baro(tas if the instance were regular python function this behavior can be obtained by simply changing the name of the value method to one of the special method names that python automatically recognizes the special method name for making an instance callable like regular python function is __call__class barometricdef __init__(selft)self self self self self # # /( * # /( *mol#kg/mol #kpa def __call__(selfh)return self exp(-self *self * /(self *self )
8,456
classes now we can call an instance of the class barometric just as any other python function baro barometric( baro( #same as baro __call__( the instance baro now behaves and looks like function the method is exactly the same as the value methodbut creating special method by renaming it to __call__ produces nicer syntax when the class is used special method for printing we are used to printing an object using print( )which works fine for python' built-in object types such as strings and lists howeverif is an instance of class we defined ourselveswe do not obtain much useful informationsince python does not know what information to show we can solve this problem by defining special method named __str__ in our class the __str__ method must return string objectpreferably string that provides useful information about the objectand it should not take any arguments except self for the function class seen abovea suitable __str__ method could look like the followingclass barometricdef __call__(selfh)return self exp(-self *self * /(self *self )def __str__(self)return ' exp(- * * /( * )) {self }if we now call print for an instance of the classthe function expression and the value of for that instance will be printedas followsb barometric( ( print(bp exp(- * * /( * )) special methods for mathematical operations so far we have seen three special methodsnamely__init____call__and __str__but there are many more we will not cover them all in this bookbut few are worth mentioning for instancethere are special methods for arithmetic operationssuch as __add____sub____mul__and so forth defining these methods inside our class will enable us to perform operations such as +bwhere , are instances of the class the following are relevant arithmetic operations and the corresponding special method that they will callc __add__(bc __sub__(bc * __mul__(
8,457
/ __div__(bc ** __pow__( it is naturalin most but not all casesfor these methods to return an object of the same type as the operands similarlythere are special methods for comparing objects,as followsa = __eq__(ba ! __ne__(ba __lt__(ba < __le__(ba __gt__(ba > __ge__(bthese methods should be implemented to return true or falseto be consistent with the usual behavior of the comparison operators the actual contents of the special method are in all cases entirely up to the programmer the only special thing about the methods is their namewhich ensures that they are automatically called by various operators for instanceif you try to multiply two objects with statement such as *bpython will look for method named __mul__ in the instance if such method existsit will be called with the instance as the argumentand whatever the method __mul__ returns will be the result of our multiplication operation the __repr__ special method the last special method we will consider here is method named __repr__which is similar to __str__ in the sense that it should return string with information about the object the difference is thatwhile __str__ should provide human-readable informationthe __repr__ string will contain all the information necessary to recreate the object for an object athe __repr__ method is called if we call repr( )where repr is built-in function the intended function of repr is such that eval(repr( )=athat isrunning the string output by __repr__ should recreate to illustrate its uselet us add __repr__ method to the class barometric from the start of the class barometricdef __call__(selfh)return self exp(-self *self * /(self *self )def __str__(self)return ' exp(- * * /( * )) {self }def __repr__(self)
8,458
classes """return code for regenerating this instance ""return 'barometric({self })againwe can illustrate how it works in an interactive shellfrom tmp import barometric( print(bp exp(- * * /( * )) repr( 'barometric( ) eval(repr( )print( exp(- * * /( * )) the last two lines confirm that the repr method works as intendedsince running eval(repr(breturns an object identical to both __repr__ and __str__ return strings with information about an objectthe difference being that __str__ gives information to be read by humanswhereas the output of __repr__ is intended to be read by python how to know the contents of class sometimes listing the contents of class can be usefulparticularly for debugging consider the following dummy classwhich does nothing useful except to define doc stringa constructorand single attributeclass """ class for demo purposes ""def __init__(selfvalue)self value if we now write dir(awe see that the class actually contains great deal more than what we put into itsince python automatically defines certain methods and attributes in all classes most of the items listed are default versions of special methodswhich do nothing useful except to give the error message notimplemented if they are called howeverif we create an instance of aand use dir on that instancewe obtain more useful informationa ( dir( ['__class__''__delattr__''__dict__''__dir__''__doc__''__eq__''__format__''__ge__''__getattribute__''__gt__''__hash__''__init__''__init_subclass__''__le__''__lt__''__module__''__ne__''__new__''__reduce__''__reduce_ex__''__repr__''__setattr__''__sizeof__''__str__''__subclasshook__''__weakref__'' 'we see that the list contains the same (mostly uselessdefault versions of special methodsbut some of the items are more meaningful if we continue the interactive session to examine some of the itemswe obtain __doc__ ' class for demo purposes
8,459
__dict__ {' ' __module__ '__main__the __doc__ attribute is the doc string we definedwhile __module__ is the name of the module to which class belongswhich is simply __main__ in this casesince we defined it in the main program howeverthe most useful item is probably __dict__which is dictionary containing the names and values of all the attributes of the object any instance holds its attributes in the self __dict__ dictionarywhich is automatically created by python if we add new attributes to the instancethey are inserted into the __dict__a ([ , ]print __dict__ all attributes {' '[ ] myvar add new attribute (! __dict__ {'myvar' ' '[ ]when programming with classes we are not supposed to use the internal data structures such as __dict__ explicitlybut printing it to check the values of class attributes can be very useful if something goes wrong in our code exampleautomatic differentiation of functions to provide more relevant and useful example of __call__ special methodconsider the task of computing the derivative of an arbitrary function given some mathematical function in pythonsaydef ( )return ** we want to make class derivative and write dfdx derivative(fso that dfdx behaves as function that computes the derivative of (xwhen the instance dfdx is createdwe want to call it like regular function to evaluate the derivative of in point xprint(dfdx( )computes * ** for = it is tricky to create such class using analytical differentiation rulesbut we can write generic class by using numerical differentiation
8,460
classes (xf ( hf (xh for small (yet moderatehsay - this estimate will be sufficiently accurate for most applications the key parts of the implementation are to let the function be an attribute of the derivative class and then implement the numerical differentiation formula in __call__ special methodclass derivativedef __init__(selffh= - )self self float(hdef __call__(selfx)fh self fself return ( ( +hf( ))/ make short forms the following interactive session demonstrates typical use of the classfrom math import df derivative(sinx pi df( - cos(xexact - def ( )return ** dg derivative(gt dg(tcompare with (exact for particularly useful application of the derivative classconsider the solution of nonlinear equation ( in we implement newton' method as general method for solving nonlinear equationsbut newton' method uses the derivative ( )which needs to be provided as an argument to the functiondef newton (fdfdxx max_it= tol - )return convergediter see for complete implementation of the function for many functions ( )finding (xcan require lengthy and boring derivationsand in such cases the derivative class is quite handydef ( )return *( )** ( )** dfdx derivative(fxstart newton (fdfdxxstart
8,461
( true test functions for classes in we introduced test functions as method to verify that our functions were implemented correctlyand the exact same approach can be used to test the implementation of classes inside the test functionwe define parameters for which we know the expected outputand then call our class methods and compare the results with those expected the only additional step involved when testing classes is that we will typically create one or more instances of the class inside the test function and then call their as an exampleconsider test function for the derivative class of the previous section how can we define test case with known output for this classtwo possible methods are(ito compute ( ( hf ( ))/ by hand for some and hor (iiutilize the fact that linear functions are differentiated exactly by our numerical formularegardless of test function based on (iicould look like the followingdef test_derivative()the formula is exact for linear functionsregardless of lambda xa* dfdx derivative(fh= diff abs(dfdx( aassert diff - 'bug in class derivativediff=%sdiff this function follows the standard recipe for test functionswe construct problem with known resultcreate an instance of the classcall the methodand compare the result with the expected result howeversome of the details inside the test function may be worth commenting on firstwe use lambda function to define (xas you may recall from lambda function is simply compact way of defining functionwith lambda xa* being equivalent to def ( )return * the use of the lambda function inside the test function appears straightforward at firstf lambda xa* dfdx derivative(fh= dfdx(
8,462
classes the function is defined to taking one argument and also using two two local variables and that are defined outside the function before it is called howeverlooking at this code in more detail can raise questions calling dfdx( implies that derivative __call__ is calledbut how can this methods know the values of and when it calls our (xfunctionthese variables are defined inside the test function and are therefore localwhereas the class is defined in the main program the answer is that function defined inside another function "remembers,or has access toall the local variables of the function where it is defined thereforeall the variables defined inside test_derivative become part of the namespace of the function fand can access and in test_derivative even when it is called from the __call__ method in class derivative this construction is known as closure in computer science examplea polynomial class as summarizing example of classes and special methodswe can consider the representation of polynomials introduced in polynomial can be specified by dictionary or list representing its coefficients and powers for example is and the coefficients can be stored as list [ - we now want to create class for such polynomial and equip it with functionality to evaluate and print polynomials and to add two polynomials intended use of the class polynomial could look like the followingp polynomial([ - ]print( polynomial([ - - ] print( coeff[ - - print( * ^ ^ print( ( )- * differentiate(print( * ^ * ^ to make all these operations possiblethe class needs the following special methods
8,463
__init__the constructorfor the line polynomial([ ,- ]__str__for doing print( __call__to enable the call ( __add__to make work __mul__to allow * in additionthe class needs method differentiate that computes the derivative of polynomialand changes it in-place starting with the most basic methodsthe constructor is fairly straightforward and the call method simply follows the recipe from class polynomialdef __init__(selfcoefficients)self coeff coefficients def __call__(selfx) for in range(len(self coeff)) +self coeff[ ]* ** return to enable the addition of two polynomialswe need to implement the __add__ methodwhich should take one argument in addition to self the method should return new polynomial instancesince the sum of two polynomials is polynomialand the method needs to implement the rules of polynomial addition adding two polynomials means to add terms of equal orderwhichin our list representationmeans to loop over the self coeff lists and add individual elementsas followsclass polynomialdef __add__(selfother)return self other start with the longest list and add in the otherif len(self coefflen(other coeff)coeffsum self coeff[:copyfor in range(len(other coeff))coeffsum[ +other coeff[ielsecoeffsum other coeff[:copyfor in range(len(self coeff))coeffsum[ +self coeff[ireturn polynomial(coeffsumthe order of the sum of two polynomials is equal to the highest order of the twoso the length of the returned polynomial must be equal to the length of the longest of the two coeff lists we utilize this knowledge in the code by starting with copy of the longest list and then looping through the shortest and adding to each element
8,464
classes the multiplication of two polynomials is slightly more complex than their additionso it is worth writing down the mathematics before implementing the __mul__ method the formula looks like ci xi dj xj ci dj xi+ = = = = whichin our list representationmeans that the coefficient corresponding to the power is ci dj the list of coefficients for the resulting polynomial should have length and an element [kshould be the sum of all products [ ]* [jfor which the implementation of the method could look like class polynomialdef __mul__(selfother) len(self coeff len(other coeff coeff [ ]*( + + or zeros( + + for in range( + )for in range( + )coeff[ + +self coeff[ ]*other coeff[jreturn polynomial(coeffjust as the __add__ method__mul__ takes one argument in addition to selfand returns new polynomial instance turning now to the differentiate methodthe rule for differentiating general polynomial is ci ici xi- dx = = thereforeif is the list of coefficientsthe derivative has list of coefficients dcwhere dc[ - * [ifor from one to the largest index in note that dc will have one element less than csince differentiating polynomial reduces the order by one the full implementation of the differentiate method could look like the followingclass polynomialdef differentiate(self)change self for in range( len(self coeff))self coeff[ - *self coeff[idel self coeff[- def derivative(self)return new polynomial dpdx polynomial(self coeff[:]copy dpdx differentiate(return dpdx
8,465
herethe differentiate method will change the polynomial itselfsince this is the behavior indicated by the way the function was used above we have also added separate function derivative that does not change the polynomial butinsteadreturns its derivative as new polynomial object finallylet us implement the __str__ method for printing the polynomial in human-readable form this method should return string representation close to the way we write polynomial in mathematicsbut achieving this can be surprisingly complicated the following implementation does reasonably good jobclass polynomialdef __str__(self) 'for in range( len(self coeff))if self coeff[ ! + {self coeff[ ]: }* ^{ : }fix layout (many special cases) replace('-''' replace( *'' replace(' ^ '' ' replace(' ^ '' 'if [ : ='remove initial [ :if [ : ='fix spaces for initial '- [ :return for all these special methodsas well as special methods in generalit is important to be aware that their contents and behavior are entirely up to the programmer the only special thing about special methods is their namewhich ensures that they are automatically called by certain operations what they actually do and what they return are decided by the programmer writing the class if we want to write an __add__ method that returns nothingor returns something completely different from sumwe are free to do so howeverit isof coursea good habit for the __add__(selfotherto implement something that seems like meaningful result of self other open access dieses kapitel wird unter der creative commons namensnennung international lizenz (in jeglichem medium und format erlaubtsofern sie den/die ursprunglichen autor(enund die quelle ordnungsgemass nenneneinen link zur creative commons lizenz beifugen und angebenob anderungen vorgenommen wurden die in diesem kapitel enthaltenen bilder und sonstiges drittmaterial unterliegen ebenfalls der genannten creative commons lizenzsofern sich aus der abbildungslegende nichts anderes ergibt sofern das betreffende material nicht unter der genannten creative commons lizenz steht und die betreffende handlung nicht nach gesetzlichen vorschriften erlaubt istist fur die oben aufgefuhrten weiterverwendungen des materials die einwilligung des jeweiligen rechteinhabers einzuholen
8,466
object-oriented programming upon reading the titleone could wonder why object-oriented programming (oopis introduced only now we have used objects since and we started making our own classes and object types in so what is new in the answer is that the term oop can have two different meanings the first simply involves programming with objects and classeswhich we introduced in and is more commonly referred to as object-based programming the second meaning of oop is programming with class hierarchieswhich are families of classes that inherit their methods and attributes from each other this is the topic of the present we will learn how to collect classes in families (hierarchiesand let child classes inherit attributes and methods from parent classes class hierarchies and inheritance class hierarchy is family of closely related classes organized in hierarchical manner key concept is inheritancewhich means that child classes can inherit attributes and methods from parent classes typical strategy is to write general class as base class (or parent classand then let special cases be represented as subclasses (child classesthis approach can often save much typing and code duplication as usualwe introduce the topic by looking at some examples classes for lines and parabolas as first examplelet us create class for representing and evaluating straight linesy following the concepts and ideas introduced in the implementation of the class can look like import numpy as np class line(cthe author( sundnesintroduction to scientific programming with pythonsimula springerbriefs on computing
8,467
object-oriented programming def __init__(selfc )self self def __call__(selfx)return self self * def table(selflrn)"""return table with points for < < "" 'for in np linspace(lrn) self(xs + '{ : { : }\nreturn we see that we have equipped the class with standard constructora __call__ special method for evaluating the linear functionand method table for writing table of and values say we now want to write similar class for evaluating parabola the code could look like class paraboladef __init__(selfc )self self self def __call__(selfx)return self * ** self * self def table(selflrn)"""return table with points for < < "" 'for in linspace(lrn) self(xs + '{ : { : }\nreturn we observe that the two classes are nearly identicaldiffering only in the parts that involve although we could very quickly just copy all the code from the line class and edit the small parts that are neededsuch duplication of code is usually bad idea at some pointwe may need change the codefor instanceto correct an error or improve the functionalityand having to make the same change in multiple places often leads to time-consuming errors sois there way we can utilize the class line code in parabola without resorting to copying and pastingthis is exactly what inheritance is about to introduce inheritancelet us first look at the following class definitionclass parabola(line)pass here pass is just python keyword that can be used wherever python expects to find codebut we do not want to define anything soat first sightthis parabola class seems to be emptybut notice the class definition class
8,468
parabola(line)which means that parabola is subclass of line and inherits all its methods and attributes the new parabola class therefore has attributes and and three methods __init____call__and table line is base class (or parent classsuperclassand parabola is subclass (or child classderived classthe new parabola classthereforeis not as useless as it first seemedbut it is still just copy of the line class to make the class represent parabolawe need to add the missing codethat isthe code that differs between line and parabola when creating such subclassesthe principle is to reuse as much as possible from the base classonly add what is needed in the subclassand avoid duplicating code inspecting the two original classes abovewe see that the parabola class must add code to line' constructor (an extra attributeand an extra term in __call__but table can be used unaltered the full definition of parabola as subclass of line becomes the followingclass parabola(line)def __init__(selfc )super(__init__( line stores self def __call__(selfx)return super(__call__(xself * ** to maximize code reusewe allow the parabola class to call the methods from lineand then add the missing parts subclass can always access its base class bt using the built-in function super()and this is the preferred way to call methods from the base class we couldhoweveralso use the class name directlyfor instance line __init__(self, , generallythese two methods for invoking superclass methods look like the followingsuperclassname method(selfarg arg super(method(arg arg notice the difference between the two approaches when using the class name directlywe need to include self as the first argumentwhereas this aspect is handled automatically when using super(the use of super(is usually preferredbut in most cases the two approaches are equivalent to summarize this first examplethe main benefits of introducing the subclass are as followsclass parabola just adds code to the already existing code in class linewith no duplication of the code for storing and and computing class parabola also has table methodit is inherited and does not need to be written __init__ and __call__ are overridden or redefined in the subclasswith no code duplication we can use the parabola class and call its methods just as if they were implemented in the class directly
8,469
object-oriented programming parabola( - ( print( print( table( )the real meaning of inheritance from practical viewpointand for the examples in this bookthe point of inheritance is to reuse methods and attributes from the base class and minimize code duplication on more theoretical levelinheritance should be thought of as an "is-arelationship between the the two classes by this we mean that if parabola is subclass of linean instance of parabola is also line instance the parabola class is thought of as special case of the line classand therefore every parabola is also linebut not vice versa we can check class type and class relations with the built-in functions isinstance(objtypeand issubclass(subclassnamesuperclassname)from line_parabola import lineparabola line(- isinstance(llinetrue isinstance(lparabolafalse parabola(- isinstance(pparabolatrue isinstance(plinetrue issubclass(parabolalinetrue issubclass(lineparabolafalse __class__ =parabola true __class__ __name__ string version of the class name 'parabolawe will not use these methods much in practical applications but they are very useful for gaining feel for class relationships when learning oop mathematically oriented readers might have noticed logical fault in the small class hierarchy we have presented so far we stated that subclass is usually thought of as special case of the base classbut parabola is not really special case of straight line it is the other way aroundsince line is parabola with could then linethenbe subclass of parabolacertainlyand many will prefer this relation between line and parabolasince it follows the usual is- relationship between subclass and its base the code can look like if you have to use isinstance in your code to check what kind of object you are working withit is usually sign that the program is poorly designed there are exceptionsbut normally isinstance and issubclass should only be used for learning and debugging
8,470
class paraboladef __init__(selfc )self self self def __call__(selfx)return self * ** self * self def table(selflrn)"""return table with points for < < "" 'for in linspace(lrn) self(xs +'% % \ (xyreturn class line(parabola)def __init__(selfc )super(__init__( notice that this version allows even more code reuse than the previous onesince both __call__ and table can be reused without changes exampleclasses for numerical differentiation common tasks in scientific computingsuch as differentiation and integrationcan be carried out with large variety of numerical methods many such methods are closely relatedand can be easily grouped into families of methods that are very suitable for implementation in class hierarchy as first examplewe consider methods for numerical differentiation the simplest formula is one-sided finite differencef (xf ( hf (xh which can be implemented in the following classclass derivativedef __init__(selffh= - )self self float(hdef __call__(selfx)fh self fself return ( ( +hf( ))/ make short forms to use the derivative classwe simply define function ( )create an instance of the classand call it as if it were regular function (effectively calling the __call__ method behind the scenes)
8,471
object-oriented programming from math import expsinpi def ( )return exp(- )*sin( *pi*xdfdx derivative(fprint(dfdx( )howevernumerous other formulas can be used for numerical differentiationfor instance ( hf (xo( ) (xf ( ho( ) (xh ( hf ( ho( ) ( ( hf ( ( hf ( ho( ) ( ( hf ( ( hf ( hf ( ( hf ( ho( ) ( hf ( hf (xf ( ho( (xh (xwe can easily make module that offers multiple formulasas followsclass forward def __init__(selffh= - )self fself fh def __call__(selfx)fh self fself return ( ( +hf( ))/ class central def __init__(selffh= - )self fself fh def __call__(selfx)fh self fself return ( ( +hf( - ))/( *hclass central def __init__(selffh= - )self fself fh def __call__(selfx)fh self fself return ( / )*( ( +hf( - )/( *
8,472
( / )*( ( + *hf( - * ))/( *hthe problem with this code isof coursethat all the constructors are identicalso we duplicate great deal of code although the duplication of this simple constructor might not be big problemit can easily lead to errors if we want to change the constructor laterand it is therefore worth avoiding as mentioned abovea general idea of oop is to place code common to many classes in superclass and to have that code be inherited by the subclasses in this casewe can make superclass containing the constructor and let the different subclasses implement their own version of the __call__ method the superclass will be very simple and not really useful on its ownclass diffdef __init__(selffh= - )self fself fh the subclasses for the first-order forward formula and the secondand fourthorder central difference formulas can then look like class forward (diff)def __call__(selfx)fh self fself return ( ( +hf( ))/ class central (diff)def __call__(self, )fh self fself return ( ( + )- ( - ))/( *hclass central (diff)def __call__(selfx)fh self fself return ( / )*( ( +hf( - )/( * ( / )*( ( + *hf( - * ))/( *hto use this simple class hierarchy in an examplesaywe want to compute the derivative of (xsin for with the fourth-order central difference formulafrom math import sinpi mycos central (sinmycos(piherethe line mycos central (sincreates an instance of the central class by calling the constructor inherited from the superclasswhile mycos(picalls the __call__ method implemented in the subclass as indicated by the (hn terms in the formulas abovethe methods have different levels of accuracy we can empirically investigate the accuracy of the numerical differentiation formulasusing the class hierarchy created above using (xsin xx / as an examplethe code can look like from diff import forward central central
8,473
object-oriented programming from math import pisincos import numpy as np [ /( **ifor in range( )ref cos(pi/ print(fh forward central central 'for h_ in hf forward (sin,h_) central (sin,h_) central (sin,h_e abs( (pi/ )-refe abs( (pi/ )-refe abs( (pi/ )-refprint( '{h_: { : { :> { :> }' forward central central notice that we create new instances and for each iteration of the loopsince we want new value of in the formula more elegant solution could be to add new method named set_stepsize(hor similarthat would allow us to adjust for an existing instance such method could easily be added to the superclass and inherited by all subclasses an examination of the output numbers confirm that the three methods behave as expected for each rowwe reduce by factor of twoand the errors are reduced by factor of about twofourand respectively this result is consistent with the theoretical accuracy of the formulaswhich states that the errors should be proportional to hh and respectively exampleclasses for numerical integration just as numerical differentiationnumerical integration is mainstay of computational mathematics there are numerous methods to choose fromand they can all be written on the form ( )dx - wi (xi = and the based on this general formuladifferent methods are realized by choosing the integration points xi and associated weights wi for instancethe trapezoidal rule has xi ihw wn- wi (  )
8,474
8,475
programming with design patterns james cooper boston columbus new york san francisco amsterdam cape town dubai london madrid milan munich paris montreal toronto delhi mexico city sao paulo sydney hong kong seoul singapore taipei tokyo
8,476
are claimed as trademarks where those designations appear in this bookand the publisher was aware of trademark claimthe designations have been printed with initial capital letters or in all capitals editor-in-chief mark taub python screenshots( - python software foundation development editor chris zahn cover imagespainter_vfx/shutterstock executive editor debra willimans screenshot of mysql workbench ( oracle corporation managing editor sandra schroeder the author and publisher have taken care in the preparation of this bookbut make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions no liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information or programs contained herein senior project editor lori lyons for information about buying this title in bulk quantitiesor for special sales opportunities (which may include electronic versionscustom cover designsand content particular to your businesstraining goalsmarketing focusor branding interests)please contact our corporate sales department at corpsales@pearsoned com or ( - for government sales inquiriesplease contact governmentsales@pearsoned com for questions about sales outside the please contact intlcs@pearson com visit us on the webinformit com/aw library of congress control number copyright ( pearson educationinc all rights reserved this publication is protected by copyrightand permission must be obtained from the publisher prior to any prohibited reproductionstorage in retrieval systemor transmission in any form or by any meanselectronicmechanicalphotocopyingrecordingor likewise for information regarding permissionsrequest forms and the appropriate contacts within the pearson education global rights permissions departmentplease visit www pearson com/permissions isbn- - - isbn- - scoutautomatedprintcode copy editor krista hansing editorial services production manager remya divakarancodemantra indexer ken johnson proofreader charlotte kughen compositor codemantra
8,477
pearson is dedicated to creating bias-free content that reflects the diversity of all learners we embrace the many dimensions of diversityincluding but not limited to raceethnicitygendersocioeconomic statusabilityagesexual orientationand religious or political beliefs education is powerful force for equity and change in our world it has the potential to deliver opportunities that improve lives and enable economic mobility as we work with authors to create content for every product and servicewe acknowledge our responsibility to demonstrate inclusivity and incorporate diverse scholarship so that everyone can achieve their potential through learning as the world' leading learning companywe have duty to help drive change and live up to our purpose to help more people create better life for themselves and to create better world our ambition is to purposefully contribute to world whereqq qq qq qq everyone has an equitable and lifelong opportunity to succeed through learning our educational products and services are inclusive and represent the rich diversity of learners our educational content accurately reflects the histories and experiences of the learners we serve our educational content prompts deeper discussions with learners and motivates them to expand their own learning (and worldviewwhile we work hard to present unbiased contentwe want to hear from you about any concerns or needs with this pearson product so that we can investigate and address them qq please contact us with concerns about any potential bias at
8,478
8,479
iintroduction introduction to objects visual programming in python visual programming of tables of data what are design patterns iicreational patterns the factory pattern the factory method pattern the abstract factory pattern the singleton pattern the builder pattern the prototype pattern summary of creational patterns iiistructural patterns the adapter pattern the bridge pattern the composite pattern the decorator pattern the facade pattern the flyweight pattern the proxy pattern summary of structural patterns
8,480
chain of responsibility pattern the command pattern the interpreter pattern the iterator pattern the mediator pattern the memento pattern the observer pattern the state pattern the strategy pattern the template pattern the visitor pattern va brief introduction to python variables and syntax in python making decisions in python development environments python collections and files functions running python programs index
8,481
iintroduction the tkinter library github introduction to objects the class __init__ method variables inside class collections of classes inheritance derived classes created with revised methods multiple inheritance drawing rectangle and square visibility of variables properties local variables types in python summary programs on github visual programming in python importing fewer names creating an object-oriented version using message boxes using file dialogs understanding options for the pack layout manager using the ttk libraries responding to user input adding two numbers catching the error applying colors in tkinter creating radio buttons using class-level variable communicating between classes using the grid layout creating checkbuttons disabling check boxes
8,482
adding menus to windows using the labelframe moving on examples on github visual programming of tables of data creating listbox displaying the state data using combobox the treeview widget inserting tree nodes moving on example code on github what are design patterns defining design patterns the learning process notes on object-oriented approaches python design patterns references iicreational patterns the factory pattern how factory works sample code the two subclasses building the simple factory using the factory simple gui factory patterns in math computation programs on github thought questions the factory method pattern the swimmer class the event classes straight seeding circle seeding xi
8,483
contents our seeding program other factories when to use factory method programs on github the abstract factory pattern gardenmaker factory how the user interface works consequences of the abstract factory pattern thought questions code on github the singleton pattern throwing the exception creating an instance of the class static classes as singleton patterns finding the singletons in large program other consequences of the singleton pattern sample code on github the builder pattern an investment tracker calling the builders the list box builder the checkbox builder displaying the selected securities consequences of the builder pattern thought questions sample code on github the prototype pattern cloning in python using the prototype consequences of the prototype pattern sample code on github summary of creational patterns
8,484
iiistructural patterns the adapter pattern moving data between lists making an adapter the class adapter two-way adapters pluggable adapters programs on github the bridge pattern creating the user interface extending the bridge consequences of the bridge pattern programs on github the composite pattern an implementation of composite salary computation the employee classes the boss class building the employee tree printing the employee tree creating treeview of the composite using doubly linked lists consequences of the composite pattern simple composite other implementation issues dealing with recursive calls ordering components caching results programs on github the decorator pattern decorating button using decorator using nonvisual decorators decorated code xiii
8,485
contents the dataclass decorator using dataclass with default values decoratorsadaptersand composites consequences of the decorator pattern programs on github the facade pattern building the facade classes creating databases and tables using the sqlite version consequences of the facade programs on github notes on mysql using sqlite references the flyweight pattern what are flyweights example code selecting folder copy-on-write objects program on github the proxy pattern using the pillow image library displaying an image using pil using threads to handle image loading logging from threads copy-on-write comparing related patterns programs on github summary of structural patterns ivbehavioral patterns chain of responsibility pattern when to use the chain sample code
8,486
the listboxes programming help system receiving the help command the first case chain or tree kinds of requests consequences of the chain of responsibility programs on github the command pattern when to use the command pattern command objects keyboard example calling the command objects building command objects the command pattern consequences of the command pattern providing the undo function creating the red and blue buttons undoing the lines summary references programs on github the interpreter pattern when to use an interpreter where the pattern can be helpful simple report example interpreting the language how parsing works sorting using attrgetter( the print verb the console interface the user interface consequences of the interpreter pattern programs on github xv
8,487
contents the iterator pattern why we use iterators iterators in python fibonacci iterator getting the iterator filtered iterators the iterator generator fibonacci iterator generators in classes consequences of the iterator pattern programs on github the mediator pattern an example system interactions between controls sample code mediators and command objects consequences of the mediator pattern single interface mediators programs on github the memento pattern when to use memento sample code consequences of the memento pattern programs on github the observer pattern example program for watching colors change the message to the media consequences of the observer pattern programs on github the state pattern sample code switching between states how the mediator interacts with the statemanager consequences of the state pattern
8,488
state transitions programs on github the strategy pattern why we use the strategy pattern sample code the context the program commands the line and bar graph strategies consequences of the strategy pattern programs on github the template pattern why we use template patterns kinds of methods in template class sample code drawing standard triangle drawing an isosceles triangle the triangle drawing program templates and callbacks summary and consequences example code on github the visitor pattern when to use the visitor pattern working with the visitor pattern sample code visiting each class visiting several classes bosses are employeestoo double dispatching traversing series of classes consequences of the visitor pattern example code on github xvii
8,489
contents va brief introduction to python variables and syntax in python data types numeric constants strings character constants variables complex numbers integer division multiple equal signs for initialization simple python program compiling and running this program arithmetic operators bitwise operators combined arithmetic and assignment statements comparison operators the input statement pep standards variable and function names constants class names indentation and spacing comments docstrings string methods examples on github making decisions in python elif is "else if combining conditions the most common mistake looping statements in python the for loop and lists using range in if statements using break and continue the continue statement python line length
8,490
the print function formatting numbers and java style formatting the format string function -string formatting comma-separated numbers strings formatting dates using the python match function pattern matching reference moving on sample code on github development environments idle thonny pycharm visual studio other development environments liclipse jupyter notebook google colaboratory anaconda wing command-line execution cpythonipythonand jython python collections and files slicing slicing strings negative indexes string prefix and suffix removal changing list contents copying list reading files using the with loop handling exceptions xix
8,491
contents using dictionaries combining dictionaries using tuples using sets using the map function writing complete program impenetrable coding using list comprehension sample programs on github functions returning tuple where does the program start summary programs on github running python programs if you have python installed shortcuts creating an executable python program command-line arguments index
8,492
when began studying pythoni was impressed by how simple coding was and how easy it was to get started writing basic programs tried several development environmentsand in all casesi was able to get simple programs running in moments the python syntax was simpleand there were no brackets or semicolons to remember other than remembering to use the tab key (to generate those four-space indentations)coding in python was easy but it was only after played with python for few weeks that began to see how sophisticated the language really is and how much you can really do with it python is fully object-oriented languagemaking it easy to create classes that hold their own data without lot of syntactic fussing in facti started trying to write some programs that had written years ago in javaand was amazed by how much simpler they were in python and with the powerful idesit was hard to make many mistakes when realized how much could get done quickly in pythoni also realized that it was time to write book about powerful programs you can write in python this led to my writing newcleanreadable versions of the classic design patterns that had originally coded some years before the result is this bookwhich illustrates the basics of object-oriented programmingvisual programmingand how to use all of the classic patterns you can find complete working code for all these programs on github at pythonpatterns this book is designed to help python programmers broaden their knowledge of object-oriented programming (oopand the accompanying design patterns qq qq qq if you are new to python but have experience in other languagesyou will be able to charge ahead by reviewing through and then starting back at if you are experienced in python but want to learn about oop and design patternsstart at if you likeyou can skip and and go right through the rest of the book if you are new to programming in generalspend some time going over through to try some of the programs then start on to learn about oop and design patterns you will likely find that python is the easiest language you ever learnedas well as the most effortless language for writing the objects you use in design patterns you'll see what they are for and how to use them in your own work in any casethe object-oriented programming methods presented in these pages can help you write bettermore reusable program code
8,493
this book is organized into five parts part "introductiondesign patterns essentially describe how objects can interact effectively this book starts by introducing objects in "introduction to objects,and providing graphical examples that clearly illustrate how the patterns work "visual programming in python,and "visual programming of tables of data,introduce the python tkinter librarywhich gives you way to create windowsbuttonsliststablesand more with minimal complexity "what are design patterns?"begins the discussion of design patterns by exploring exactly what they are part ii"creational patternspart ii starts by outlining the first group of patterns that the "gang of fournamed creational patterns "the factory pattern,describes the basic factory patternwhich serves as the simple basis of the three factory patterns that follow in this you create factory class that decides which of several related classes to usebased on the data itself "the factory method pattern,explores the factory method in this patternno single class makes the decision as to which subclass to instantiate insteadthe superclass defers the decision to each subclass "the abstract factory pattern,discusses the abstract factory pattern you can use this pattern when you want to return one of several related classes of objectseach of which can return several different objects on request in other wordsthe abstract factory is factory object that returns one of several groups of classes "the singleton pattern,looks at the singleton patternwhich describes class in which there can be no more than one instance it provides single global point of access to that instance you don' use this pattern all that oftenbut it is helpful to know how to write it in "the builder pattern,you see that the builder pattern separates the construction of complex object from its visual representationso that several different representations can be createddepending on the needs of the program "the prototype pattern,shows how to use the prototype pattern when creating an instance of class is time consuming or complex instead of creating more instancesyou make copies of the original instance and modify them as appropriate "summary of creational patterns,just summarizes the patterns in part ii
8,494
part iii begins with short discussion of structural patterns "the adapter pattern,examines the adapter patternwhich is used to convert the programming interface of one class into that of another adapters are useful whenever you want unrelated classes to work together in single program "the bridge pattern,takes up the similar bridge patternwhich is designed to separate class' interface from its implementation this enables you to vary or replace the implementation without changing the client code "the composite pattern,delves into systems in which component may be an individual object or may represent collection of objects the composite pattern is designed to accommodate both casesoften in treelike structure in "the decorator pattern,we look at the decorator patternwhich provides way to modify the behavior of individual objects without having to create new derived class although this can apply to visual objects such as buttonsthe most common use in python is to create kind of macro that modifies the behavior of single class instance in "the facade pattern,we learn to use the facade pattern to write simplifying interface to code that otherwise might be unduly complex this deals with such an interface to couple of different databases "the flyweight pattern,describes the flyweight patternwhich enables you to reduce the number of objects by moving some of the data outside the class you can consider this approach when you have multiple instances of the same class "the proxy pattern,looks at the proxy patternwhich is used when you need to represent an object that is complex or time consuming to createby simpler one if creating an object is expensive in time or computer resourcesproxy enables you to postpone creation until you need the actual object "summary of structural patterns,summarizes these structural patterns part iv"behavioral patternspart iv outlines the behavioral patterns "chain of responsibility pattern,looks at how the chain of responsibility pattern allows decoupling between objects by passing request from one object to the next in chain until the request is recognized "the command pattern,shows how the command pattern uses simple objects to represent the execution of software commands additionallythis pattern enables you to support logging and undoable operations "the interpreter pattern,looks at the interpreter patternwhich provides definition of how to create little execution language and include it in program
8,495
the formal ways you can move through collection of data items "the mediator pattern,takes up the important mediator pattern this pattern defines how communication between objects can be simplified by using separate object to keep all objects from having to know about each other "the memento pattern,saves the internal state of an objectso you can restore it later in "the observer pattern,we look at the observer patternwhich enables you to define the way number of objects can be notified of change in program state "the state pattern,describes the state patternwhich allows an object to modify its behavior when its internal state changes "the strategy pattern,describes the strategy patternwhichlike the state patternswitches easily between algorithms without any monolithic conditional statements the difference between the state and strategy patterns is that the user generally chooses which of several strategies to apply in "the template pattern,we look at the template pattern this pattern formalizes the idea of defining an algorithm in class but leaves some of the details to be implemented in subclasses in other wordsif your base class is an abstract classas often happens in these design patternsyou are using simple form of the template pattern "the visitor pattern,explores the visitor patternwhich turns the tables on the object-oriented model and creates an external class to act on data in other classes this is useful if there are fair number of instances of small number of classes and you want to perform some operation that involves all or most of them part " brief introduction to pythonin this last section of the bookwe provide succinct summary of the python language if you are only passingly familiar with pythonthis will get you up to speed it is sufficiently thorough to instruct beginner as well in "variables and syntax in python,we review the basic python variables and syntaxand in "making decisions in python,we illustrate the ways your programs can make decisions in "development environments,we provide short summary of the most common development environmentsand in "python collections and files,we discuss arrays and files finally in "functions,we take up how to use functions on python enjoy writing design patterns and learning the ins and outs of the powerful python language
8,496
8,497
must start by thanking the late john vlissidesone of the original "gang of four,for his clear explanations of several points about these design patterns he worked just few doors down from me at ibm research and didn' mind my dropping in for chat about patterns from time to time also really appreciated early supportive comments from arianne dee and ausif mahmoodas well as vaughn cooper of coursemy editordebra williamshas been both supportive and creative in helping me bring this project to fruitionas have the reviewersnick cohron and regina monaco and from development point of viewchris zahn has been terrific hope you enjoy writing patterns in python as much as have james cooper wiltonct july
8,498
james cooper holds phd in chemistry and worked in academiafor the scientific instrument industryand for ibm for yearsprimarily as computer scientist at ibm' thomas watson research center now retiredhe is the author of booksincluding on design patterns in various languages his most recent books are flameoutthe rise and fall of ibm instruments ( and food myths debunked ( james holds patents and has written columns for javapro magazine he has also written nearly , columns for the now vanished examiner com on foods and chemistryand he currently writes his own blogfoodscienceinstitute com recentlyhe has written columns on python for medium com and substack he is also involved in local theater groups and is the treasurer for troupers light operawhere he performs regularly
8,499