id
int64
0
25.6k
text
stringlengths
0
4.59k
8,300
template methodself-delegation "the essence of oopsome of its many python-specific variants
8,301
great patternlousy name "templatevery overloaded generic programming in +generation of document from skeleton better nameself-delegation directly descriptive!-
8,302
abstract base class offers "organizing methodwhich calls "hook methodsin abchook methods stay abstract concrete subclasses implement the hooks client code calls organizing method on some reference to abc (injecteror which of course refers to concrete sc
8,303
class abstractbase(object)def orgmethod(self)self dothis(self dothat(class concrete(abstractbase)def dothis(self)def dothat(self)
8,304
def cmdloop(self)self preloop(while trues self doinput( self precmd(sfinis self docmd(sfinis self postcmd(finis,sif finisbreak self postloop(
8,305
the "organizing methodprovides "structural logic(sequencing &cthe "hook methodsperform "actual ``elementary'actionsit' an often-appropriate factorization of commonality and variation focuses on objects(classes'responsibilities and collaborationsbase class calls hookssubclass supplies them applies the "hollywood princip...
8,306
class thebase(object)def dothis(self)provide default (often no-oppass def dothat(self)orforce subclass to implement (might also just be missing raise notimplementederror default implementations often handierwhen sensiblebut "mandatorymay be good docs
8,307
class queuedef put(selfitem)self not_full acquire(trywhile self _full()self not_full wait(self _put(itemself not_empty notify(finallyself not_full release(def _put(selfitem)
8,308
not abstractoften used as-is thusimplements all hook-methods subclass can customize queueing discipline with no worry about lockingtimingdefault discipline is simpleuseful fifo can override hook methods (_init_qsize_empty_full_put_getand data (maxsizequeue) python special
8,309
class lifoqueuea(queue)def _put(selfitem)self queue appendleft(itemclass lifoqueueb(queue)def _init(selfmaxsize)self maxsize maxsize self queue list(def _get(self)return self queue pop(
8,310
"organizing methodin one class "hook methodsin another kuhtml formatter vs writer kusax parser vs handler adds one axis of variability/flexibility shades towards the strategy dpstrategy abstract class per decision pointindependent concrete classes factored tmabstract/concrete classes more "grouped
8,311
"organizingclass can snoop into "hookclass (maybe descendantat runtime find out what hook methods exist dispatch appropriately (including "catchalland/or other error-handling
8,312
def docmd(selfcmda)tryfn getattr(self'do_cmdexcept attributeerrorreturn self dodefault(cmdareturn fn(
8,313
es bartlett learning(cjonesllc bartlett learning llcan ascend learning company not for sale or distribution not for sale or distribution or sale or distribution (cjones bartlett learningllc not for sale or distribution (cjones bartlett learningllc not for sale or distribution es bartlett learningllc or sale or distribu...
8,314
es bartlett learning(cjonesllc bartlett learning llcan ascend learning company not for sale or distribution not for sale or distribution or sale or distribution (cjones bartlett learningllc not for sale or distribution (cjones bartlett learningllc not for sale or distribution es bartlett learningllc or sale or distribu...
8,315
es bartlett learning(cjonesllc bartlett learning llcan ascend learning company not for sale or distribution not for sale or distribution or sale or distribution (cjones bartlett learningllc not for sale or distribution contents (cjones bartlett learningllc not for sale or distribution (cjones bartlett learn not for sal...
8,316
es bartlett learning(cjonesllc bartlett learning llcan ascend learning company not for sale or distribution not for sale or distribution or sale or distribution vi contents (ccodes jonesand bartlett learningllc (cjones bartlett learn other secrets not for sale or dist not for sale or distribution objectives the string ...
8,317
es bartlett learning(cjonesllc bartlett learning llcan ascend learning company not for sale or distribution not for sale or distribution or sale or distribution contents vii ( )reading jones bartlett learningdata&from the internet llc (cjones bartlett learn using csv files not for sale or dist not for sale or distribut...
8,318
es bartlett learning(cjonesllc bartlett learning llcan ascend learning company not for sale or distribution not for sale or distribution or sale or distribution viii contents (ccryptanalysis jones bartlett learningllc (cjones bartlett learn not for sale or dist not for sale or distribution objectives introduction crack...
8,319
es bartlett learning(cjonesllc bartlett learning llcan ascend learning company not for sale or distribution not for sale or distribution or sale or distribution contents ix ( )summary jones bartlett learningllc (cjones bartlett learn key terms not for sale or dist not for sale or distribution python keywords and functi...
8,320
es bartlett learning(cjonesllc bartlett learning llcan ascend learning company not for sale or distribution not for sale or distribution or sale or distribution ( jonescreating bartlett learn your ownlearningvideo game llc (cjones bartlett the lasercannon class not for sale or dist not for sale or distribution the boun...
8,321
es bartlett learning(cjonesllc bartlett learning llcan ascend learning company not for sale or distribution not for sale or distribution or sale or distribution (cjones bartlett learningllc not for sale or distribution preface (cjones bartlett learningllc not for sale or distribution introduction (cjones bartlett learn...
8,322
es bartlett learning(cjonesllc bartlett learning llcan ascend learning company not for sale or distribution not for sale or distribution or sale or distribution xii preface (cjones bartlett learningllc that are methods of (cjones bartlett learn in students learn about writing functions class in not for sale or dist not...
8,323
es bartlett learning(cjonesllc bartlett learning llcan ascend learning company not for sale or distribution not for sale or distribution or sale or distribution preface >(cjones bartlett so learningllc all python code is&color-coded the student can better see syntax elements not for sale or distribution def getmax(alis...
8,324
es bartlett learning(cjonesllc bartlett learning llcan ascend learning company not for sale or distribution not for sale or distribution or sale or distribution xiv preface (cjones bartlett learningllc how to use this text not for sale or distribution organization (cjones bartlett learn not for sale or dist th text is ...
8,325
es bartlett learning(cjonesllc bartlett learning llcan ascend learning company not for sale or distribution not for sale or distribution or sale or distribution preface (cjones bartlett learningllc not for sale or distribution introducing introduction codes and pthonthe python to python other secrets estimating pi coll...
8,326
es bartlett learning(cjonesllc bartlett learning llcan ascend learning company not for sale or distribution not for sale or distribution or sale or distribution xvi preface ( )>jones bartlett llc can be used as homework(cjoneswe&have bartlett learn in traditional lecture learningcoursethe exercises problems not for sal...
8,327
langtangen
8,328
dear readerour aim with the series simula springerbriefs on computing is to provide compact introductions to selected fields of computing entering new field of research can be quite demanding for graduate studentspostdocsand experienced researchers alikethe process often involves reading hundreds of papersand the metho...
8,329
this book was originally written as set of lecture notes to the book primer on scientific programming with python by hans petter langtangen and can be used either as supplement to that book or on its ownas compact introduction to scientific programming langtangen' book and these lecture noteshave formed the core of an ...
8,330
preface broader set of topics and includes more examplesmore detailed discussions and explanationsand many more useful programming hints and tips highly recommend it as supplement to these notes for anyone with ambitions to become an expert scientific programmer the present book was written specifically for the course ...
8,331
xi in and he wrote the book on which these notes are based throughout these lecture notes have extensively copied ideaspresentation styleand code examples from his original booksimply because find them excellent for introducing programming in scientific context if it were not for hans petter would clearly never have wr...
8,332
preface ix getting started with python the first examplehelloworld different ways to use python computing with formulas programming simple mathematics variables and variable types formatting text output importing modules pitfalls when programming mathematics loops and lists loops for automating repetitive tasks boolean...
8,333
contents user input and error handling reading user input data flexible user input with eval and exec reading data from files writing data to files handling errors in programs making modules arrays and plotting numpy and array computing plotting curves with matplotlib plotting discontinuous and piecewise-defined functi...
8,334
getting started with python this book teaches the python programming languagewhich is one of the most popular languages for introductory programming courses an advantage of python is that it is so-called high-level languagewith simple and intuitive syntax that makes it easy to get started howeveralthough it works well ...
8,335
getting started with python appear in the terminal right after the command if you are using an ideit is essentially an editor and an ipython/terminal window combined for instancein the popular spyder ide the editor is usually in the upper left windowwhile the window in the lower right corner is the ipython window where...
8,336
third way to use python is through jupyter notebookswhich are form of interactive notebooks that combine code and text the notebooks are viewed through browser and look quite similar to simple web pagebut with the important difference that the code segments are "livepython code that can be runchangedand re-run while re...
8,337
getting started with python 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 vorgenom...
8,338
computing with formulas in this we will go one step beyond the helloworldexample of the first and introduce programming with mathematical formulas such formulas are essential parts of most programs written for scientific applicationsand they are also useful for introducing the concept of variableswhich is fundamental p...
8,339
computing with formulas interest py in regular terminal or run interest py in an ipython window or spyder the interest py program is not much more complex or useful than the helloworldexample from the previous but there are couple of important differences firstnotice thatin this case we did not use quotation marks insi...
8,340
use whitespace in order to make the code as readable as possible to humanssince python will ignore it anyway variables and variable types we are used to variables in mathematicssuch as and in the interest formula above we can use variables in program tooand this makes the program easier to read and understandprimary am...
8,341
computing with formulas for instancea is different from the following program is identical to the one abovebut with different variable namesinitial_amount interest_rate number_of_years final_amount initial_amount*( interest_rate/ )**number_of_years print(final_amountthese variable names are arguably more descriptivebut...
8,342
comments are useful for explaining the thought process in programs it is possible to combine the strengths of the two programs above and have both compact variable names and more detailed description of what each variable means this can be done using commentsas illustrated in the following exampleprogram for computing ...
8,343
computing with formulas we see that the output is as expected from the definitions of these variables above the word class preceding the types indicates that these types are defined as classes in pythona concept we will return to later it is usually not necessary to check the type of variables inside python programbut ...
8,344
of courseusing float to convert string to number requires that the string actually be number trying to convert regular wordas in float(hellowill make the program stop with an error message there are numerous other built-in functions for converting between typessuch as int for conversion to an integer and str for conver...
8,345
computing with formulas extra more specificallythe string could contain expressions or variables enclosed in curly bracketsand we have included two such variablesn and amount when python encounters the curly brackets inside an -stringit will evaluate the contents of the curly bracketswhich can be an expression or varia...
8,346
columns in the table are properly aligned similar feature can be used for integersr print( "integer set to occupy exactly chars of spacer { : }"integer set to occupy exactly chars of spacer finallythe generic format specifier outputs floating point number in the most compact forma print( "without the format specifiera ...
8,347
computing with formulas natural question to ask is why we need three different ways to import module why not use the simple from math import and gain access to all the mathematics functions we needthe reason is that we will often import from several modules in the same programand some of these modules can contain funct...
8,348
contentswe can go to straight to the python library referencebut there are also other options the command pydoc in the terminal window can be used to list information about module (trye pydoc math)or we can import the module in python program and list its contents with the built-in function dir import math print(dir(ma...
8,349
computing with formulas false true we see that the evaluation works as expected in one casebut not the otherand this is general problem when comparing floating point numbers in most cases the evaluation worksbut in some cases it does not it is difficult or impossible to predict when it will not workand the behavior of ...
8,350
terminal terminalpython python (defaultsep : : print(#the parentheses are optional in python print( / integer division is useful for many tasks in computer scienceand is therefore the default behavior of many programming languagesbut it is usually not what we want when programming mathematical formulas thereforeit coul...
8,351
loops and lists in this programming starts to become useful the concepts introduced in the previous are essential building blocks in all computer programsbut our example programs only performed few calculationswhich we could easily do with regular calculator in this we will introduce the concept of loopswhich can be us...
8,352
loops and lists how can we make program that writes such tablewe know from the previous how to generate one line in the tablep ( + / )** print( ,awe could then simply repeat these statements to write the complete programp = = ( + / )**nprint( ,an= ( + / )**nprint( ,an= ( + / )**nprint( ,an= ( + / )**nprint( ,athis is o...
8,353
pass of the looplooking at the task definition abovewe should be able to answer all of these questions(ithe loop should start at zero yearsso our initial condition should be (iithe statements to be repeated are the evaluation of the formula and the printing of and (iiiwe want the loop to stop when reaches yearsso our c...
8,354
loops and lists and the condition in python codethese are written as = ! > note the double == is an assignmentnotice the use of the double =when checking for equality as we mentioned in the single equality sign has different meaning in python (and many other programming languagesthan we are used to from mathematicssinc...
8,355
boolean expressions are important for controlling the flow of programsboth in while loops and in other constructs that we will introduce in their evaluation and use should be fairly familiar from mathematicsbut it is always good idea to explore fundamental concepts such as this by typing in few examples in an interacti...
8,356
loops and lists mylist [ - print(mylist[ ]print(mylist[ ]print(mylist[ ]len(mylistlength of list the last line uses the built-in python function lenwhich returns the number of elements in the list this function works on lists and any other object that has natural length ( strings)and is very useful other built-in list ...
8,357
iterating over list with for loop having introduced listswe are ready to look at the second type of loop we will use in this bookthe for loop the for loop is less general than the while loopbut it is also bit simpler to use the for loop simply iterates over elements in listand performs operations on each onefor element...
8,358
loops and lists update any variables inside it the for loop will simply iterate over given listperform the operations we want on each elementand then stop when it reaches the end of the list tasks of this kind are very commonand for loops are extensively used in python programs the observant reader might notice that th...
8,359
using the function range to loop over indices sometimes we do not have listbut want to repeat the same operation given number of times if we know the number of repetitions this task is an obvious candidate for for loopbut for loops in python always iterate over an existing list (or list-like objectthe solution is to us...
8,360
loops and lists amounts [for in range( + ) *( + / )** amounts append(aprint(amountsstart with empty list add new element to amounts list the parts worth noting in this code are amounts []which simply creates list with no elementsand the use of the append function inside the for loop to add elements to the list this sim...
8,361
as demonstrated by this small programthe result is not what we want we added the value of two to every elementbut after the loop finishedour list was unchanged the reason for this behavior is that although the list is traversed as desired when we create the for loop using for in :the variable is an ordinary (intvariabl...
8,362
loops and lists the resulting lists a_low and a_high are exactly the same as those from the for loopbut the code is obviously much more compact to an experienced python programmerthe use of list comprehensions also makes the code more readablesince it becomes obvious that the code creates listand the contents of the li...
8,363
nested lists and list slicing as described abovelists in python are quite general and can store any objectincluding another list the resulting list of lists is often referred to as nested list instead of storing the amounts resulting from the low and high interest rates above as two separate listswe could put them toge...
8,364
loops and lists for in range(len(somelist[ ][ ]))value somelist[ ][ ][ work with value although their logic is the same as regular (one-dimensionalfor loopsnested loops look more complicated and it can take some time to fully understand how they work as noted abovea good way to obtain such understanding is to create so...
8,365
list in the interactive python shell and explore the effect of various slicing operations it isof course ,possible to combine list slicing with nested listsand the results can be confusing even to experienced python programmers fortunatelywe will consider only fairly simple cases of list slicing in this bookand we will...
8,366
loops and lists typeerror'tupleobject doesn' support item deletion the observant reader might wonder why the line (- - in the example above workssince is supposed to be immutable and therefore impossible to change the answer is related to the way assignment statements work in programming as briefly explained in assignm...
8,367
functions and branching this introduces two fundamental programming conceptsfunctions and branching we are used to functions from mathematicswhere we typically define function (xas some mathematical expression of xand then we can then evaluate the function for different values of xplot the curve ( )solve equations of t...
8,368
functions and branching and we also used functions that were bound to specific objectsand accessed with the dot syntaxfor instanceappend to add elements to listc [ append( this last type of function is quite specialsince it is bound to an objectand operates directly on that object ( append changes cthese bound function...
8,369
the function' arguments (sometimes called parametersthis simple function takes single argumentbut we can define functions that take multiple arguments by separating the arguments with commas the parentheses need to be thereeven if we do not want the function to take any argumentsin which case we would just leave the pa...
8,370
functions and branching print( print(amount( )call a_list [amount(yearfor year in range( )#multiple calls the call amount(nfor some argument returns float objectwhich essentially means that amount(nis replaced by this float object we can therefore make the call amount(neverywhere float can be used note thatunlike many ...
8,371
argument names in the callas in = = or simply pass the values if we specify the namesthe order of the arguments becomes arbitraryas in the last call above arguments that are passed without specifying the name are called positional argumentsbecause their position in the argument list determines the variable to which the...
8,372
functions and branching local variables are foundas for and in this casethese values are used if some variables are not found in the local namespacepython will move to the global namespaceand look for global variables that match the given names if variable with the right name is found among the global variablesthat isi...
8,373
in this casethe global is changed the keyword global tells python that we do want to change global variableand not define new local one as general ruleone should minimize the use of global variables inside functions andinsteaddefine all the variables used inside function either as local variables or as arguments passed...
8,374
functions and branching callpositionvelocity yfunc( as abovethe return arguments are separated by commaand we assign the values to the two global variables position and velocityalso separated by comma when function returns multiple values like thisit actually returns tuplethe immutable list type defined in the previous...
8,375
#example use from math import log print( ( ) ( )-log( - )the output from the print statement indicates that the approximation improves as the number of terms is increasedas is usual for such approximating series for many purposesit would be useful if the function returned the error of the approximationthat isln( xl(xn)...
8,376
functions and branching def table( )print( ' ={ }-ln( - )={-log( - )}'for in [ ]valueerror (xnprint( ' ={ : dapprox{value: }error{error: }'table( = -ln( - )= approx error approx error approx error approx error this function does not need to return anythingsince entire purpose is to print information to the screen defau...
8,377
default values are used hello [ true somefunc('hello'[ , ]'hi'hello [ hi kwarg has default value somefunc('hello'[ , ]'hi' hello [ hi kwarg has default value somefunc('hello'[ , ]kwarg ='hi'#kwarg hello [ true hi kwarg has default value somefunc('hello'[ , ]kwarg ='hi'kwarg = hello [ hi specify all args using what we n...
8,378
functions and branching another point on the line (floatsreturnab (floatsfor the line ( = * + "" ( )/( * return ab doc strings do not take much time to writeand are very useful for others who want to use the function widely accepted convention in the python communitydoc strings are also used by various tools for automa...
8,379
thatunlike the functions seen so farthis function has two return statements this is perfectly valid and is quite common in functions with if-tests when return statement is executedthe function call is over and any following lines in the function are simply ignored thereforethere is usually no point in having multiple r...
8,380
functions and branching < <= < ( <= < >= which in python can be implemented with multiple if-else-branching def ( )if return elif < return elif < return elif > return in later we will see multiple examples of more general use of branchingnot restricted to mathematics or piecewise-defined functions inline if-tests for s...
8,381
should work with an arbitrary ( )which is most conveniently accomplished by passing python function (xas an argument to the function consider the example of approximating the second derivative (xby centered finite differencesf (xf ( (xf ( hh the corresponding python function looks like def diff (fxh= - ) ( ( - * (xf( +...
8,382
functions and branching from two lines to one line one answer is that the lambda function definition can be placed directly in the argument list of the other function instead of first defining (xand then passing it as an argumentas in the code abovewe can combine these tasks into one linedf diff (lambda xx** - , print(...
8,383
elsea ( + )/ return #call the method for ( ) ** - * +exp(-xf lambda xx** - * +exp(-xsol bisection( ,- , , - print( ' {sol:gis an approximate rootf({sol: }{ (sol): }'we see that the bisection function takes four argumentsthe mathematical function (ximplemented as python functionthe bounds for our initial intervaland the...
8,384
functions and branching /dfdx( ( return #call the method for ( ) ** - * +exp(-xf lambda xx** - * +exp(-xdfdx lambda * - -exp(-xsol newton( ,dfdx, , - print( ' {sol:gis an approximate rootf({sol: }{ (sol): }'notice how the variable is updated inside the loop the algorithm only needs to know the value at one iteration to...
8,385
writing test functions to verify our programs in the first part of this we mentioned the idea of writing tests to verify that functions work as intended this approach to programming can be very effectiveand although we spend some time writing the testswe often save much more time by the fact that we discover errors ear...
8,386
functions and branching assert statementthe text string msgis optional and is simply included to give more meaningful error message if the test fails if we leave this outand only write assert successwe will see general message stating that the test has failed ( so-called assertion error)but without much information abo...
8,387
return sin(xelsereturn def test_f() exp - exp pi/ exp tol - assert abs( ( )-exp tolf'failed for { }assert abs( ( )-exp tolf'failed for { }assert abs( ( )-exp tolf'failed for { }note here thatsince we compare floating point numberswhich have finite precision on computerwe compare with tolerance rather than the equality ...
8,388
functions and branching working on the same codebut can also be quite useful for your own projects the recommended and most widely used tool is called pytest or py testwhere pytest is simply the new name for py test we can run pytest from the terminal windowand pass it either file name or folder name as an argumentas i...
8,389
user input and error handling so farall the values we have assigned to variables have been written directly into our programs if we want different value of variablewe need to edit the code and rerun the program of coursethis is not how we are used to interacting with computer programs usuallya program will receive some...
8,390
user input and error handling altitude hp - / where is the pressure at sea level kpaand is the so-called scale height kma python program for evaluating this formula could look like from math import exp #sea level pressure (kpa#scale height (mh exp(- / print(pof coursewe are usually interested in evaluating the formula ...
8,391
running the program in terminal window could look liketerminal terminalpython altitude py input the altitude (in meters) notice in particular the line float( )which is an example of the type conversions mentioned in the input function will always return text stringwhich must be converted to an actual number before we c...
8,392
user input and error handling way of providing input and modifying program behavior we will make our python programs do the sameand write programs that can be run as terminal terminalpython myprog py arg arg arg where arg arg arg and so forth are input arguments to the program we again consider the air pressure calcula...
8,393
running this program in different ways illustrates how the list worksfor instanceterminal terminalpython print_cml py string with blanks ['print_cml py'' ''string''with''blanks'' 'terminalpython print_cml py "string with blanks ['print_cml py'' ''string with blanks'' 'we see from the second example thatif we want to re...
8,394
user input and error handling herethe line eval(sis equivalent to writing + but using eval gives much more flexibilityof coursesince the string is stored in variable and can be read as input small python program using eval can be quite flexible considerfor instancethe following code eval(input('operand ') eval(input('o...
8,395
operand one traceback (most recent call last)file "add_input py"line in eval(input('operand ')file ""line in nameerrorname 'oneis not defined in the first of these exampleswe try to add tuple and listwhich one could easily imagine would workbut python does not allow this and therefore the program breaks in the second e...
8,396
user input and error handling we can also use exec to execute multiple statementsfor instance using multi-line stringssomecode ""def ( )term exp(- * )*sin( *xterm *sin( *xreturn term term ""exec(somecodeexecute the string as python code herethe exec line will simply execute the string somecodejust as if we had typed th...
8,397
the derivative of function (xcan be approximated with centered finite differencef ( hf ( hf ( for some small the implementation of the diff py program could look like from math import import sys formula sys argv[ code ""def ( )return {formula""exec(codex float(sys argv[ ]def numerical_derivative(fxh= - )return ( ( +hf(...
8,398
user input and error handling the basic way to read file in python is to use the function openwhich takes file name as an argument the following code illustrates its useinfile open('data txt'' 'for line in infiledo something with line infile close(open file close file herethe first line opens the file data txt for read...
8,399
the use of with to open files is quite popularand you are likely to see it in python programs you encounter the keyword with has other uses in python that we will not cover in this bookbut it is particularly common and convenient for reading files and therefore worth mentioning here to actually read file after it has b...