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 principle""don' call uswe'll call you
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 distribution for my wifejaneand my childrenkaia and joshua (cjones bartlett learningllc --bnm not for sale or distribution for my wifebrendaand my three childrenkelseyhannahand rylea --dlr (cjones bartlett learningllc forsale my husbandtommy childrenbrian not for or distribution and jonmy daughter-in-lawsilviaand my grandchildren suribenand reyna --jaa (cjones bartlett learningllc not for sale or distribution (cjones bartlett learningllc not for sale or distribution es bartlett learningllc or sale or distribution es bartlett learningllc (cjones bartlett learn not for sale or dist (cjones bartlett learningllc not for sale or distribution (cjones bartlett learningllc not for sale or distribution (cjones bartlett learningllc not for sale or distribution (cjones bartlett learningllc not for sale or distribution (cjones bartlett learn not for sale or dist (cjones bartlett learn not for sale or dist (cjones bartlett learningllc not for sale or distribution (cjones bartlett learningllc
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 distribution (cjones bartlett learningllc not for sale or distribution (cjones bartlett learningllc not for 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 distribution es bartlett learningllc (cjones bartlett learn not for sale or dist (cjones bartlett learningllc not for sale or distribution (cjones bartlett learningllc not for sale or distribution (cjones bartlett learningllc not for sale or distribution (cjones bartlett learningllc not for sale or distribution (cjones bartlett learn not for sale or dist (cjones bartlett learn not for sale or dist (cjones bartlett learningllc not for sale or distribution (cjones bartlett learningllc
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 sale or dist (cjones bartlett learningllc not for sale or distribution preface xi introduction to python objectives es bartlett learningllc (cjones bartlett learningllc what is computer science or sale or distribution why study computer sciencenot for sale or distribution everyday applications of computer science why computer science is important problem-solving strategies python overview primitive elements (cjones objects bartlett learningllc (cjones naming bartlett learn for abstraction not for sale or dist not sale or distribution repetition summary key terms python keywords programming exercises (cjones bartlett learningllc pthonestimating pi not for sale or distribution (cjones bartlett learningllc not for sale or distribution objectives what is pi more about the math module the archimedes approach the python implementation es bartlett learningjones bartlett learningllc llc developing function to compute(cpi accumulator approximations for sale or distribution or sale or distribution not the accumulator pattern summation of termsthe leibniz formula product of termsthe wallis formula monte carlo simulation boolean expressions (cjones bartlett learningllc (cjones compound boolean expressions and logical operators bartlett learn selection statements not for sale or dist not for sale or distribution completing the implementation adding graphics summary key terms python keywordsmodules and commands programming exercises llc (cjones bartlett learning (cjones bartlett learningllc not for sale or distribution es bartlett learningllc not for sale or distribution (cjones bartlett learningllc
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 data type concatenation repetition indexing string slicing (cjones bartlett learningllc (cjones bartlett learningstring searching llc string methods not for sale or distribution not for sale or distribution character functions encoding and decoding messages transposition cipher encrypting using transposition decrypting transposed message es bartlett learningllc asking for input (cjones bartlett learningllc substitution cipher not for sale or distribution or sale or distribution creating key the vigenere cipher summary key terms new python keywordsfunctionsand constants (cjonesprogramming bartlett learninglearn llc (cjones bartlett exercises not for sale or distribution introducing the python collections not for sale or dist objectives what is data storing data for processing strings revisited (cjones bartlett learningllc (cjones bartlett learningllc lists not for sale or distribution calculating statistics on data not for sale or distribution simple dispersion central tendency mean median mode es bartlett learning llcfrequency distribution (cjones bartlett learningllc using dictionary to compute frequency table or sale or distribution not for sale or distribution computing frequency table without dictionary visualizing frequency distribution dispersionstandard deviation summary key terms keywordsfunctionsand methods jones bartlett (cjonespython bartlett learningllc (clearn programming exercises not for sale or distribution not for sale or dist bigger datafile / objectives using files for large data sets text files (cjones bartlett learningllc (cjones bartlett learningiterating over lines in file llc writing file not for sale or distribution not for sale or distribution string formatting alternative file-reading methods es bartlett learningllc (cjones bartlett learningllc
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 distribution using while loop to process data list comprehension reading json data from the internet correlating data summary key terms llc (cjones bartlett (cjones bartlett learninglearningllc python keywords and functions not for sale or distribution not for sale or programming exercise distribution image processing objectives what is digital image processing es bartlett learning(cjones bartlett learningllc llc the rgb color model the cimage module or sale or distribution not for sale or distribution basic image processing negative images grayscale general solutionthe pixel mapper parametersparameter passingand scope call by&assignment parameter passing bartlett learn (cjones bartlett learningllc (cjones namespaces not for sale or dist not sale and or distribution for calling functions finding names modules and namespaces advanced image processing resizing stretchinga different perspective flipping an image (cjones bartlett learningllc (cjones bartlett learningllc edge detection not for or distribution sale summary not for sale or distribution key terms python keywordsfunctionsand variables programming exercises learningdata miningcluster analysis es bartlett llc (cjones bartlett learningllc objectives or sale or distribution not for sale or distribution what is data mining cluster analysisa simple example implementing cluster analysis on simple data distance between two points (cjones &and bartlett learningllc (cjones clusters centroids bartlett learn the -means cluster analysis algorithm not for sale or dist not for sale or distribution implementation of -means implementation of -meanscontinued implementing cluster analysisearthquakes file processing visualization cluster analysis shortcomings bartlett (cjones bartlett learningllcand solutions (cjones learningllc summary not for sale or distribution not for sale or distribution key terms python keywords programming exercises es bartlett learningllc (cjones bartlett learningllc
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 cracking the rail fence checking our work with dictionary brute-force solution rail fence decryption algorithm (cjones bartlett learningllc (cjones bartlett learningllc cracking the substitution cipher not for sale or distribution not for sale or distribution letter frequency ciphertext frequency analysis letter pair analysis word frequency analysis pattern matching with partial words regular expression summary es bartlett learning llcsummary (cjones bartlett learningllc key terms not for sale or distribution or sale or distribution python functionsmethodsand keywords programming exercises fractalsthe geometry of nature objectives ( ) jonesintroduction bartlett learningllc (cjones bartlett learn not for sale or distribution recursive programs not for sale or dist recursive squares classic recursive functions drawing recursive tree the sierpinski triangle call tree for sierpinski triangle (cjones bartlett learningllc snowflakeslindenmayerand grammars (cjones bartlett learning llc -systems not for sale or distribution not for sale or distribution automatically expanding production rules more advanced -systems summary key terms programming exercises es bartlett learningllc planet objects or sale or distribution (cjones bartlett learningllc not for sale or distribution es bartlett learningllc (cjones bartlett learningllc objectives introduction programming object-oriented programming python classes ( ) jonesdesigning bartlett learningllcclass (clearn and implementing planet jones bartlett constructor method not for sale or dist not for sale or distribution accessor methods mutator methods special methods methods and self details of method storage and lookup designing andllc implementing sun class (cjones bartlett learning llc (cjones bartlett learning designing and implementing solar system not for sale or distribution not for sale or distribution animating the solar system using turtles planetary orbits implementation
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 functions programming exercises simulation objectives llc (cjones bartlett (cjones bartlett learninglearningllc bears and fish not for sale or distribution not for sale or distribution what is simulation rules of the game design implementation the world class es bartlett learning(cjones bartlett learningllc the fish class llc the bear class or sale or distribution not for sale or distribution main simulation growing plants note on inheritance summary key terms keywords and functions llc (cjones bartlett learn ( )python jones bartlett learningprogramming exercises not for sale or distribution father was rectangle not for sale or dist objectives introduction (cjones bartlett learninglearningllc first design llc (cjones bartlett sale basicor implementation not for sale or distribution not for distribution the canvas class the geometricobject class the point class the line class testing our implementation understanding bartlett learningllc es bartlett learningllc inheritance (cjones limitations or sale or distribution not for sale or distribution an improved implementation implementing polygons summary key terms python keywordsmethodsand decorator learningllc (cjones bartlett learn ( )programming jones &exercises bartlett not for sale or distribution video games not for sale or dist objectives introduction event-driven programming simulating an event loop (cjones bartlett learningllc (cjones bartlett learningllc multithreaded event loop not for sale or distribution not for sale or event-driven programming with the turtle distribution simple etch- -sketch using key presses placing turtles using mouse clicks bouncing turtles es bartlett learningllc (cjones bartlett learningllc
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 boundedturtle class the drone class the bomb class putting all the pieces together summary key terms llc (cjones bartlett learning llc (cjones bartlett learningpython keywords and decorator not for sale or programming distribution exercises not for sale or distribution appendix installing the required software appendix python quick reference appendix bartlett learningllc es bartlett learningllc turtle reference (cjones or sale or distribution not"try for sale or distribution appendix answers to selected it outexercises index (cjones bartlett learningllc not for sale or distribution (cjones bartlett learningllc not for sale or distribution es bartlett learningllc or sale or distribution (cjones bartlett learningllc not for sale or distribution (cjones bartlett learningllc not for sale or distribution (cjones bartlett learningllc not for sale or distribution (cjones bartlett learningllc not for sale or distribution es bartlett learningllc (cjones bartlett learn not for sale or dist (cjones bartlett learn not for sale or dist (cjones bartlett learningllc not for sale or distribution (cjones bartlett learningllc
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 not for sale or dist (cjones bartlett learningllc not for sale or distribution computer science deals with people who have problems to solve algorithms help fi the solutions to those problems to be computer scientist means fi st and foremost that you are problem solveres bartlett learningllcalgorithms either from scratch (cjones bartlett learningllc capable of constructing or by applying patterns from past experience or sale orthe distribution not for sale or distribution only way to be successful in learning computer science is through deliberate and incremental exposure to the fundamental ideas of the discipline beginning student of computer science needs practice to establish thorough understanding of concept before continuing on to the more complex parts of the curriculum in additiona beginner needs the opportunity to be successful and to gain confide ce as through the introductory want bartlett learn ( )students jonesprogress bartlett learningllccomputer science sequence(cwe jones them to focusnot on aspects of problem solvingalgorithm developmentand algorithm understanding not for sale or dist for sale or distribution in this textwe use python as the programming language because it has cleansimple syntax and an intuitive user environment the basic collections are powerfulyet easy to use the interactive nature of the language creates place to test ideas without the need for lot of coding finallypython provides textbook-like notation for representing algorithmsalleviating the need (cjones bartlett llc jones bartlett learningllc for an additional layerlearningof pseudocode th allows the illustration of( )many relevantmodernand notinteresting for sale or distribution not for sale or distribution problems that make use of algorithms key features th slearningtext is designed to be fi st course in computer on problem solving,llc with es bartlett llc (cscience jonesthat &focuses bartlett learninglanguage features being introduced as needed to solve the problem at hand we have structured or sale or distribution not for sale or distribution the text around problems of general interestrather than traditional language-element structure thusyou will not see titles in this text like "loopsand "conditionals"--but you will see titles such as "planet objectsand "codes and other secrets th oughout the textconcepts are introduced using spiral model because the syntax of (cjones bartlett learningllc (cjones bartlett learn python is easy to learnwe can quickly introduce the basics of standard programming constructs not for not for sale distribution as students progress through the text,or more of the details and background for these constructs are sale or dist added to their toolbox in this waystudents are exposed to important computer science concepts at the point when those concepts are needed to solve problem an illustration of how this spiral approach touches on specific topic in different ways can be seen in our presentation of functions students parameters in earning (cjones bartlett learningllc begin to write functions( )with jones bartlett llc then introduces functions with return values in students learn about passing notfor sale or distribution not for sale or distribution functions as parameters to other functions and the details of python' scoping rules in they encounter python' keyword and optional parameters covers recursive functions xi es bartlett learningllc (cjones bartlett learningllc
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 for sale or distribution students learn to write abstract methods what' new in the third edition third edition contains many in python version learningllc (cjones &thbartlett learningllc updates and new features( )found jones bartlett while keeping the problem-solving approachwe have also added pedagogical aids in not for sale or distribution not formany sale or distribution the third edition to better illustrate and highlight python programming constructs as an exampleeach newly introduced function or method is summarized in table formattablellc the input function (cjones bartlett learningllc es bartlett learningor sale or distribution not for sale or distribution function description input(promptoutputs the promptthen returns string containing any characters typed by the user when the user presses enter or return the enter or return key is not part of the returned (cjones bartlett learningllc (cjones bartlett learn string not for sale or dist not for sale or distribution in additionthe following elements are all new to this edition>recap boxes summarize important points (cjones bartlett learningllc (cjones bartlett learningllc not for sale or distribution not for orasdistribution recapa list is sequential collection of heterogenous objects listssale are written comma-delimited values enclosed in square brackets >heads up boxes alert students to possible pitfalls and provide techniques for avoiding es bartlett learningerrors llc or sale or distribution (cjones bartlett learningllc not for sale or distribution heads upbe careful to update the while loop condition in the loop body to avoid an infinite loop (cjones bartlett learningllc (cjones bartlett learn >good programming practice boxes provide problem-solving strategiesas well as tips for not for sale or dist notwriting forreadablesalemaintainable or distribution code good programming practiceuse top-down design to break large problem into smallermanageable tasks this process is also called stepwise refinement (cjones bartlett learningllc not for sale or distribution es bartlett learningllc (cjones bartlett learningllc not for sale or distribution (cjones bartlett learningllc
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(alist)maxsofar alist[ for pos in range( len(alist))if alist[posmaxsofar(cjones bartlett learningllc maxsofar alist[posnot for sale return or distribution maxsofar >xiii (cjones bartlett learn not for sale or dist (cjones bartlett learningllc not for sale or distribution figures are also presented in color--an important improvement for several turtle applications and image processing programs in which color is used to highlight variations in data es bartlett learningllc or sale or distribution (cjones bartlett learningllc not for sale or distribution (cjones bartlett learningllc not for sale or distribution (cjones bartlett learningllc not for sale or distribution es bartlett learningllc (cluka hercigonja/shutterstock or sale or distribution (cjones bartlett learn not for sale or dist (cjones bartlett learningllc not for sale or distribution (cjones bartlett learningllc not for sale or distribution as response to instructor and student feedbackwe added appendix dwhich provides answers to selected within-try it out exercises >in bigger datawe updated the approaches for accessing online data new (cjones learningllc (cjones bartlett learn examples process thebartlett popular online data formatscsv and json not for sale or dist sale distribution >alsonot startingfor in weor updated string formattingwe now use the string format method >in the planet objects and beyondwhen we create classeswe define the instance variable names using the prefix to achieve encapsulation >and function namesllc now follow standard camel-case scheme bartlett learningllc (cjones &variable bartlett learning(cjones >not for sale or distribution es bartlett learningllc not for sale or distribution (cjones bartlett learningllc
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 organized into three parts - introduce all of the key control structures and python data typesemphasizing straightforward imperative programming constructs (cjones &such bartlett learningllc bartlett as variablesloopsand conditionals by the end of (cthejones fi st five all oflearningthe major llc not for python sale data or types distribution not for sale or distribution have been covered--including integersfl atsstringslistsdictionariestuplesand files in the fi st we introduce the idea of an object as something you can use in senseprogramming in python is an objects-always approach students begin by using common programming concepts,llc while employing the modules (cthatjones python provides theselearningmodules allow us to address es bartlett learningbartlett llc more interesting problems without introducing unnecessary complexity for examplewe cover or sale or distribution not for sale or distribution simple graphics in by using turtle graphics module in we cover image processing through the use of simple image object that automatically loads an image from file but allows the students to get and set the values of pixels the next provide more details about the concepts introduced in - (cjones bartlett learningllc ( )basic jones bartlett learn - provide students with an opportunity to get more comfortable with programming not for not for sale or distribution concepts while introducing additional problem-solving patterns students also learn moresale about or dist the internal mechanisms of python the last emphasize object-oriented programming and introduce the concepts needed to design and build classes when these topics are introducedstudents are comfortable with the of usinglearningan objectin turnbuilding their own objects is( ) jones natural next step our fi learningst examples llc (cjones &idea bartlett llc bartlett emphasize the importance of interactions between multiple real-world objects after implementing not for sale or distribution not for sale or distribution simple classeswe introduce inheritance in natural way by creating graphics library and by implementing video games as an extension of the turtle module usingllc the text es bartlett learning(cjones bartlett learningllc or sale or distribution not for sale or distribution th text can be used in several ways figure provides an overview of some possibilities one path is to move through the text sequentially instructors could either cover the entire text in single semester orbecause there is enough exploratory material to last an entire yearinstructors could cover the material in two semesters second path would be to cover - and then ( )tojones bartlett learningllc jones bartlett learn move & - th approach provides balance between imperative( )and object-oriented programming that fits easily into single semester if instructors have additional timethey can pick or dist not for sale not for sale or distribution and choose from - before continuing to - another suggestion would be to teach - in an introductory course that covers only imperative programming and the use of objects (cjones bartlett learningllc not for sale or distribution es bartlett learningllc (cjones bartlett learningllc not for sale or distribution (cjones bartlett learningllc
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 collections basic control structures and all core data types using (cjones bartlett learningllc objects not for sale or distribution es bartlett learningllc image data miningor sale or distribution processing cluster analysis cryptanalysis fractalsthe geometry of nature xv (cjones bartlett learn not for sale or dist bigger datafile / (cjones bartlett learningllc not for sale or distribution (cjones bartlett learningllc not for planetsale objects or distribution simulation father was rectangle (cjones bartlett learningllc video games (cjones bartlett learn object-oriented developmentmore detail and practice core concepts not for sale or dist not for on sale or distribution building your own classes and data structures figure road map (cjones bartlett learningllc notusing for sale or distribution the exercises (cjones bartlett learningllc not for sale or distribution th text includes three kinds of exercises firstsome try it out exercises ask students to run the code that has been presented as part of the section with these exercisesstudents use the code to learn or explore on their own secondother try it out exercises have students modify or extend es bartlett learningllc (cjones &the bartlett learningllc the code provided in the section many times simple version of code is provided and students or sale are orasked distribution not for sale distribution to modify the code to improve it or add additional features thi ,or programming exercises at the end of each describe complete projects these projects are related to the materials covered in the but do not extend or modify the code already provided th oughout the text we have included exercises within each section these exercises are structured so (cthat they can&bebartlett used in several waysllc jones learning(cjones bartlett learn >>if you are reading text asor self-studythe try it out exercises provide breaking points not for sale or dist not forthis sale distribution where you have the opportunity to stop reading and practice the concepts instructors may find that many of the exercises contain material to cover in lecture that complements the material the students have read (cjones bartlett learningllc not for sale or distribution es bartlett learningllc (cjones bartlett learningllc not for sale or distribution (cjones bartlett learningllc
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 sale or dist nothad for sale or distribution good luck in the introductory computer science course using many small programming assignments often the students are able to do more than small programming assignments during single semester >we have also used this text as part of "hands-onintroduction to computer science small amount of lecture points&of bartlett but the (cjones bartlett learningllccan be used to reinforce the( )main jones learningllc majority of the class time is used to work on the exercises that complement the reading not for sale or distribution not for sale or distribution this approach follows growing trend in active learning computer science education and was well received by our students key topics es bartlett learningllc by (cjones bartlett learningllc or sale or distribution not for sale orwith distribution table maps the problems that are introduced in each the key computer science concepts that are established in the (cjones bartlett llc table problems and learningkey concepts not for sale or distribution problem key (cjones bartlett learn not for sale or dist computer science concepts numeric data typesassignment drawing polygons and statementsusing turtle approximating circleobjectssimple for loopscommon problem-solving (cjones bartlett learningllc (cjones bartlett learningllc simple functions strategies introduction to python not for sale or distribution pthonestimating pi es bartlett learningllc or sale or distribution codes and other secrets not for sale or distribution various methods for approximating pi accumulator patternsimple selection statementsboolean expressionsfunctions that return valuesmath modulerandom module llc (cjones bartlett learningnot for salestring or distribution cipher algorithms-data type and methodstranspositionsubstitution modulo arithmeticuser inputalgorithms selection and iteration with strings (cjones bartlett learningllc introducing computing simple the python statistics not for sale or distribution collections bigger datafile / computing statistics with larger data sets (cjones bartlett learningllc not for sale or distribution es bartlett learningllc (cjones bartlett learn python listtupleand dictionary data types not for sale or dist file input and outputwhile loopsstring formattingreading online data in csv and json (cjones bartlett learningllc formats not for sale or distribution (cjones bartlett learningllc
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 methodsresults and notation styles used often vary considerablywhich makes for time-consuming and potentially frustrating experience the briefs in this series are meant to ease the process by introducing and explaining important concepts and theories in relatively narrow fieldand by posing critical questions on the fundamentals of that field typical brief in this series should be around pages and should be well suited as material for research seminar in well-defined and limited area of computing we have decided to publish all items in this series under the springeropen frameworkas this will allow authors to use the series to publish an initial version of their manuscript that could subsequently evolve into full-scale book on broader theme since the briefs are freely available onlinethe authors will not receive any direct income from the saleshoweverremuneration is provided for every completed manuscript briefs are written on the basis of an invitation from member of the editorial board suggestions for possible topics are most welcome and can be sent to aslak@simula no january prof aslak tveito ceo dr martin peters executive editor mathematics springer heidelberggermany vii
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 introductory course on scientific programming at the university of oslo (inf /in etcs creditsthe course has been running since and is primarily taken by first-year students of mathematicsengineeringphysicschemistryand geosciences the writing of these lecture notesand their subsequent evolution into bookwere primarily motivated by two factors the first was that many students found the nearly pages of langtangen' book bit overwhelming as first introduction to programming this effect could be mostly psychologicalsince the book is well structured and suited for selective study of and sectionsbut the student feedback from students still indicated the need for more compact and (literallylightweight introduction the second factor was thatsadlyhans petter langtangen passed away in and his book has therefore not been updated to the newest versions of python and the various tools introduced in the book this issue could also be mostly mental obstaclesince the differences between the python versions are quite smalland only minor edits are needed to make most of the examples from the original book run on the newest python platform howeverthe book is intended as an introduction to programmingand when learning an entirely new topicany minor inconsistency is potential source of confusion therefore saw the need for an updated document where all the code examples would run without any modifications on the most common python platforms that saidin spite of these minor shortcomings as an introductory textlangtangen' book is still an excellent resource on scientific programming in python compared with the present bookit covers much hans petter langtangena primer on scientific programming with python th editionspringer-verlag ix
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 introduction to programming for scientific applications (in at the university of oslo it follows exactly the same teaching philosophy and general structure as langtangen' original bookwith the overarching idea that the only way to learn to program is to write programs reading theory is usefulbut without actual programming practicethe value is very limited the in course is therefore largely based on problem solving and programming exercisesand this book' main purpose is to prepare the students for such tasks by providing brief introduction to fundamental programming concepts and python tools the presentation style is compact and pragmaticand includes large number of code examples to illustrate how new concepts work and are applied in practice the examples are combination of pieces of code (so-called code snippets)complete python programsand interactive sessions in python shell readers are encouraged to run and modify the codes to gain feel for how the various programming concepts work source code for most of the examplesas well as jupyter notebooks for all the is provided in the online resources accompanying this book the typical reader of the book will be student of mathematicsphysicschemistryor other natural scienceand many of the examples will be familiar to these readers howeverthe rapidly increasing relevance of data science means that computations and scientific programming will be of interest to growing group of users no typical data science tools are presented in this bookbut the reader will learn tasks such as reading data from filessimple text processingand programming with mathematics and floating point computations these are all fundamental building blocks of any data science applicationand they are essential to know before diving into more advanced and specialized tools no prior knowledge of programming is needed to read this book we start with some very simple examples to get started with programming and then move on to introduce fundamental programming concepts such as loopsfunctionsif-testslistsand classes these generic concepts are supplemented by more specific and practical tools for scientific programmingprimarily plotting and array-based computations the book' overall purpose is to introduce the reader to programming andin particularto demonstrate how programming can be an extremely useful and powerful tool in many branches of the natural sciences many people have contributed to this bookin particular my colleagues at simula research laboratory and the university of oslo howeverthe contributions of professor hans petter langtangen stand head and shoulders above everyone else he has been an extremely inspiring teachermentorand colleague throughout my scientific careerhe developed the course that is now
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 written these notes would probably not be writing this either if he had notsadlypassed away in there would be no need tobecause he would surely have written far better and more extensive book himself may joakim sundnes
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 expressions using lists to store sequences of data iterating over list with for loop nested lists and list slicing tuples functions and branching programming with functions function arguments and local variables default arguments and doc strings if-tests for branching the program flow functions as arguments to functions solving equations with python functions writing test functions to verify our programs xiii
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 functions making movie of plot more useful array operations dictionaries and strings dictionaries examplea dictionary for polynomials examplereading file data to dictionary string manipulation classes basics of classes protected class attributes special methods exampleautomatic differentiation of functions test functions for classes examplea polynomial class object-oriented programming class hierarchies and inheritance exampleclasses for numerical differentiation exampleclasses for numerical integration index
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 as beginner' languagepython is also suitable for more advanced tasksand it is currently one of the most widely used programming languages worldwide the first examplehelloworldmost introductory books on programming start with so-called helloworldprogramwhich is program that simply writes helloworldto the screen in pythonthis program is just single lineprint("helloworld!"to actually write and run such programpython offers number of different options throughout this book we will mostly apply the classical programming approachwhere program is written in text editor and stored as file that is then run from the command line window or an integrated development environment (ideto write and run the "helloworld!"-program aboveopen your favorite editor (atomgeditemacs etc )type the given line and save the file with suitable filenamefor instancehello py thenopen terminal or an ipython windownavigate to the directory where you saved the fileand type python hello pyif you are using regular terminalor run hello py if you are using ipython the output helloworldshould we do not describe the technical details of acquiring and installing python heresince this information is platform dependent and becomes outdated very quickly for updated hints on installing pythonsee the web page for the in course at the university of oslo (or to the numerous other resources found online (cthe author( sundnesintroduction to scientific programming with pythonsimula springerbriefs on computing
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 you run the program although the "helloworld!"-program could seem like silly exampleit serves number of useful purposes first of allrunning this small program will verify that you have installed python properlyand that you have installed the right version it also introduces the function printwhich will be used virtually every time we programand it illustrates how we use quotes to define string in python while print is word that python understandsthe words "helloand "worldare not by using the quoteswe tell python that it should not try to understand (or interpretthese wordsbutrathertreat them as simple text thatin this caseis to be printed to the screen we will come back to this topic in more detail later different ways to use python as briefly mentioned abovepython offers some alternatives to the traditional style of programming using text editor and terminal windowand some of these alternatives can be very useful when learning to program for instancewe can use python interactively by simply typing python or ipython in terminal windowwithout subsequent file name this will open an environment for typing and running python commandswhich is not very suitable for writing programs over several linesbut extremely useful for testing python commands and statementsor simply using python as calculator in regular terminal window on macos or linuxan interactive version of the helloworldexample would look something like terminal terminalipython python (defaultmar : : type 'copyright''creditsor 'licensefor more information ipython -an enhanced interactive python in [ ]print("helloworld!"helloworldin [ ]the two versions python and ipython work largely the same waybut ipython has number of additional features and is recommended for detailsseefor instance
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 reading the document these features are particularly useful for teaching purposessince detailed explanations of new concepts are easily combined with interactive examples all the of this book are also available as jupyter notebooks minor drawbacks of the python language although python is very popular and suitable language for learning to programit also has some minor drawbacks one of the more important is tightly linked to its advantage of being flexible high-level language with short and intuitive syntax writing small programs in python can be very efficientand beginners can quickly start writing useful programsbut the downside is that the code can become messy as the programs grow in size and complexity other languages such as cc++and java tendto enforce more structure in the codewhich can be confusing for beginners and annoying when you want to write small program quicklybut it can be more efficient in the long run when writing larger programs howeverit is certainly possible to write neat and nicely structured programs in python as wellbut this requires choice by the programmer to follow certain principles of coding styleand is not enforced by the language itself another slightly annoying aspect of python is that it exists in different versions at the time of this writingpython has been dominant for quite whilebut if you look for programming resources online or read older textbooksyou will find many examples using python for the mathematicscentered programming covered in this bookthe difference between python and python is actually quite smallbut some differences are important to be aware of the most obvious one is how print works in python the program above would read print "helloworld!"that iswithout the parentheses since nearly all code examples use print to some extentprograms written in python will typically not run in python one particularly relevant resource for scientific python (on which this book is largely basedis " primer on scientific programming with python"by hans petter langtangen howeverthe latest version of that book was written in and all the code examples are in python and will stop with an error message if they are run in python in most casesthe only error is the missing parenthesesso the addition of parentheses to all the print statements will make most of the examples run fine in python we will comment on some of the other differences between the python versions later hans petter langtangena primer on scientific programming with python th editionspringer-verlag
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 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,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 part of all programming languages programming simple mathematics to introduce the concepts of this we first consider simple formula for calculating the interest on bank deposita ( ( / )) where is the initial deposit (the principal) is the yearly interest rate given in percentn is the number of yearsand is the final amount the task is now to write program that computes for given values of and we couldof courseeasily do so with calculatorbut small program can be much more flexible and powerful to evaluate the formula abovewe first need to assign values to and nand then make the calculation choosingfor instancep and complete python program that does the calculation and outputs the result reads print( *( )** as described in the previous this line can be typed into an interactive python sessionor written in an editor and stored in filefor instance interest py the program is then run with the command python (cthe author( sundnesintroduction to scientific programming with pythonsimula springerbriefs on computing
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 inside the parentheses this is because we want python to evaluate the mathematical formulaand print the result to the screenwhich works fine as long as the text inside the parentheses is valid python codeormore preciselya valid expression that can be evaluated to produce result if we put quotation marks around the formula abovethe code would still workbut the result is not what we want try itat this pointit is also worth noting thatwhile we stated above that python is flexible and high-level languageall programming languages are extremely picky about spelling and grammar considerfor instance the line write( *( + , / )^ while most people can read this line quite easilyand interpret it as the same formula as the one aboveit makes no sense as python program there are multiple errorswrite is not legal python word in this contexta comma has another meaning than the decimal pointand the hat does not mean exponentiation we have to be extremely accurate with how we write computer programsand it takes time and experience to learn this the mathematical formula above is evaluated according to the standard rules the terms are evaluated one by onefrom left to rightwith exponentiation performed first and then multiplication and division we use parentheses to control the order of the evaluationjust as we do in regular mathematics the parentheses around ( means that this sum is evaluated first (to obtain )and then raised to the power of forgetting the parenthesis and writing ** will produce very different resultjust as in mathematics because the use of parentheses to group calculations works exactly as in mathematicsit is not very difficult to understand for people with mathematical background howeverwhen programming more complicated formulas it is very easy to make mistakes such as forgetting or misplacing closing parenthesis this mistake is probably the most common source of error when programming mathematical formulasand it is worth paying close attention to the order and number of parentheses in the expressionseven for experienced programmers getting this principle wrong will lead to either an error message when the code is run or to program that runs fine but produces unexpected results the first type of error is usually quite easy to find and fixbut the latter can be much harder although python is quite strict on spelling and grammarin programming terms called the syntaxthere is some flexibility for instancewhitespace inside formula does not matter at all an expression like * works just as well as * generallywhitespace in python program only matters if it is at the start of linewhich we will return to later otherwiseone should
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 amount primary ( + / )** print(amountthis program spans several lines of text and uses variablesbut otherwise performs the same calculations and produces the exact same output as the one-line program above stillthe use of variables has few advantageseven in this very simple example one is that the program becomes easier to readsince the meaning of the numbers becomes more intuitive and the formula is easier to recognize another advantagewhich could be more importantis that it becomes easier to change the value of one of the variables this advantage becomes even more obvious in more complex formulas where the same variable occurs multiple times having to change the code in multiple places each time new value is needed is guaranteed to introduce errors if the same number occurs more than once in programit should always be stored in variable the instructions in the program above are called statementsand are executed one by one when the program is run it is common to have one statement per linealthough it is possible to put multiple statements on one lineseparated by semicolonsas in primary = for people new to programmingespecially those used to reading mathematicsit is worth noting the strict sequence in which the lines are executed in the mathematical equation abovewe first introduced the formula itselfand then defined and explained the variables used in the formula (prnand aon the next line this approach is completely standard in mathematicsbut it makes no sense in programming programs are executed line by line from the topso so all the variables must be defined above the line where they are used the choice of variable names is up to the programmer andgenerallythere is great flexibility in choosing such names in mathematicsit is common to use single letter for variablebut variable in python program can be any word containing the letters -za-zunderscore and the digits - but it cannot start with digit variable names in python are also case-sensitive
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 they also make the formula very long and cumbersome to read choosing good variable names is often balance between being descriptive and concisenessand the choice can be quite important for making program easy to read and understand writing readable and understandable code is obviously important if you collaborate with others who have to understand your codebut it also makes it easier for you to find errors in the code or develop it further at later stage choosing good variable names is therefore worthwhileeven if you are the only person who will ever read your code the program above contains two different types of statementsfirst there are four assignment statementswhich assign values to variablesand then single print statement at the end how these statements work might be quite intuitivebut the assignment statements are worth looking into in more detail in these statementsthe expression on the right-hand side of the equality sign is evaluated firstand then the result is assigned to the variable on the left an effect of this execution order is that statements such as the following work just fineand are common in programst print( the line would not make sense as mathematical equationbut it is perfectly valid assignment in computer program the right-hand side is evaluated firstusing the value of already definedand then the variable is updated to hold the result of the calculation the equality sign in python is called the assignment operatorandalthough it works similarly to an equality sign in mathematicsit is not quite the same if we want the more usual meaning of the equality signfor instanceto determine if two numbers are equalthe operator to use in python is = trivial comparison could look like print( = true we will see many more such examples later
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 the growth of money deposited in bank primary initial amount interest rate in the number of years amount primary ( + / )** print(amountin this codeall the text following the symbol is treated as comment and effectively ignored by python comments are used to explain what the computer instructions meanwhat the variables representand how the programmer reasoned when writing the program they can be very useful for increasing readabilitybut they should not be over-used comments that say no more than the codefor instancea set to are not very useful all variables have types so far all the variables we have used have been numberswhich is also how we are used to thinking of variables in mathematics howeverin computer program we can have many different kinds of variablesnot just numbers more preciselya variable is name for python objectand all objects have type the type of variable python is usually decided automatically based on the value we assign to it for instancethe statement will create variable of the type integeror intwhereas will create variable with type floatrepresenting floating point number we can also have text variablescalled stringswhich have type str for instancethe helloworldexample above could have been written as hello "helloworld!print(hellohere we create variable hellowhich automatically gets type strand then print the contents of this variable to the screen the output is exactly the same as for the first example of we can check the type of variable using the built-in function typeprint(type(hello)print(type( )print(type(primary)print(type( )
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 it could be very useful when learning new concepts or if your program produces errors or unexpected behavior we will encounter many more variable types in subsequent the type of variable decides how it can be usedand also determines the effects of various operations on that variable the rules for these operations are usually quite intuitive for instancemost mathematical operations only work with variable types that actually represent numbersor they have different effect on other variable typeswhen this is natural for an idea of how this works in pythonthink about some simple mathematical operations on text strings which of the following operations do you think are allowedand what are the results(iadding two strings together(iimultiplying string with an integer(iiimultiplying two stringsand (ivmultiplying string with decimal numberafter giving some thought to this questioncheck your answers by trying them in pythonhello "helloworld!print(hello helloprint(hello* strings that contain numbers are potential source of confusion consider for instance the code " print( + print( + we see that the variable is treated as text string in pythonbecause it was defined using the quotation markseven though it contains single number for the examples we have seen so farit is easy to ensure that numbers are numberssimply by not using quotation marks when they are defined howeverlater in this bookwe will write programs that read data from files or user input such data will usually be in the form of textand any numbers will be text strings similar to the variable above before using the numbers in calculationswe therefore need to convert them to actual numberswhich can be done with the built-in function floatx float( float( print(type( )print(type( )print( +
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 conversion to string throughout this book we will mostly use the float conversion formatting text output the calculations in the programs above would output single numberand simply print this number to the screen in many cases this solution is finebut sometimes we want several numbers or other types of output from program this is easy to do with the print functionby simply putting several variables inside the parenthesesseparated by comma for instanceif we want to output both primary and final_amount from the calculation abovethe following line would workprint(primary,final_amount howeveralthough this line worksthe output is not very readable or useful sometimes better output format or combination of text and numbers is more usefulfor instanceafter years eur has grown to xxx eur there are multiple ways to obtain this result in pythonbut the most recent and arguably most convenient is to use so called -stringswhich were introduced in python if you are using an earlier version of pythonthe following examples will not workbut there are alternative and fairly similar ways of formatting the text output to achieve the output string aboveusing the -string formattingwe would replace the final line of our program by with print( "after {nyears eur has grown to {amounteur "after years eur has grown to eur there are couple of things worth noticing here firstwe enclose the output in quotation marksjust as in the helloworldexample abovewhich tells python that this is string secondthe string is prefixed with the letter fwhich indicates that the string is an -string that could contain something
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 variableand insert the resulting value into the string the process is often referred to as string interpolation or variable interpolationand it exists in various forms in many programming languages in our casepython will simply insert the current values of the variables and amount into the stringbutif desiredwe can also include mathematical expression inside the bracketssuch as print( " + { + }" + the only requirement for the contents inside the curly brackets is that it be valid python expression that can be evaluated to yield some kind of value throughout this book we will typically use -string formatting to insert combining text and numbersbut it may also be used for expressions with other types of output the -string formatting will often produce nicely formatted output by defaultbut sometimes more detailed control of the formatting is desired for instancewe might want to control the number of decimal places when outputting numbers this is conveniently achieved by including format specifier inside the curly brackets considerfor instancethe following codet print( "default output gives { "print( "we can set the precisiont { "print( "or control the number of decimalst { "default output gives we can set the precisiont or control the number of decimalst there are many different format specifiersfor controlling the output format of both numbers and other types of variables we will use only small subset in this bookand primarily to control the formatting of numbers in addition to those shown abovethe following format specifiers can be usefulprint( "we may set the space used for the outputt { : "we may set the space used for the outputt this specifier is used to control the number of decimalsas well as how much space (the number of charactersused to output the number on the screen here we have specified the number to be output with two decimal places and length of eightincluding the decimal places this form of control is very useful for outputting multiple lines in tabular formatto ensure that the
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 { } { "print( "with the format specifiera { : } { : "without the format specifiera with the format specifiera + importing modules we have seen that standard arithmetic operations are directly available in pythonwith no extra effort howeverwhat if more advanced mathematical operationssuch as sin xcos xln xare requiredthese functions are not available directlybut can be found in so-called modulewhich must be imported before they can be used in our program generallya great deal of functionality in python is found in such modulesand we will import one or more modules in nearly all the programs we write standard mathematical functions are found in module named mathand the following code computes the square root of number using the sqrt function in the math moduleimport math math sqrt( or from math import sqrt sqrt( or from math import import everything in math sqrt( this example illustrate three different ways of importing modules in the first onewe import everything from the math modulebut everything we want to use must be prefixed with math the second option imports only the sqrt functionand this function is imported into the main namespace of the programwhich means it can be used without prefix finallythe third option imports everything from math into the main namespaceso that all the functions from the module are available in our program without prefix
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 functions with identical names in these cases it is useful to have some control over which functions are actually usedeither by selecting only what we need from each moduleas in from math import sqrtor by importing with import math so that all the functions must be prefixed with the module name to avoid confusion laterit might be good to get into the habit of importing modules in this manner right awayalthoughin small programs where we import only single modulethere is nothing wrong with from math import as another example of computing with functions from mathconsider evaluating the bell-shaped gaussian function  - exp ( ps for and for this calculationwe need to import the square rootthe exponential functionand from the math moduleand the python code may look as followsfrom math import sqrtpiexp /(sqrt( *pi)*sexp(- *(( - )/ )** print(fnotice that for this more complex formula it is very easy to make mistakes with the parentheses such errors will often lead to an error message that points to syntax error on the next line of your program this can be confusing at firstso it is useful to be aware of if you obtain an error message pointing to line directly below complex mathematical formulathe source is usually missing closing parenthesis in the formula itself finding information about python modules at this pointit is natural to ask how we know where to find the functions we want say we need to compute with complex numbers how can we know if there is module in python for thisandif sowhat is it calledgenerallylearning about the useful modules and what they contain are part of learning python programmingbut knowing where to find such information could be even more important an excellent source is the python library reference (the standard modules that are distributed with python more generallya google search for complex numbers python quickly leads us to the cmath modulewhich contains mostly the same functions as mathbut with support for complex numbers if we know the name of module and want to check its
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(math)['__doc__''__file__''__loader__''__name__' pitfalls when programming mathematics usuallythe mathematical operations described above work as expected when the results are not as expectedthe cause is usually trivial error introduced during typingtypically assigning the wrong value to variable or mismatching the number of parentheses howeversome potential error sources are less obvious and are worth knowing abouteven if they are relatively rare round-off errors give inexact results computers have inexact arithmetic because of rounding errors this is usually not problem in computationsbut in some cases it can cause unexpected results let usfor instancecompute / and / * * print( "{ { }"the output with decimal places becomes most real numbers are represented inexactly on computertypically with an accuracy of digits neither / nor / are represented exactlyand the error is approximately - errors of this order usually do not matterbut there are two particular cases in which they can be significant in one caseerrors can accumulate through numerous computationsending up as significant error in the final result in the other casewhich is more likely to be encountered in the examples of this bookthe comparison of two decimal numbers can be unpredictable the two numbers and above are both supposed to be equal to onebut look at the result of this codeprint( = print( =
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 the program thus becomes unpredictable the solution is to always compare floats by using tolerance valueas in tol - print(abs( - tolprint(abs( - toltrue true there is no strict rule for setting the value of the tolerance tolhoweverit should be small enough to be considered insignificant for the application at handbut larger than the typical machine precision - some words are reserved and cannot be used as variables although the choice of variable names is up to the programmersome names are reserved in python and are not allowed to be used these names are andasassertbreakclasscontinuedefdelelifelseexceptexecfinallyforfromglobalifimportinislambdanotorpassprintraisereturntrywithwhileand yield memorizing this list is by no means necessary at this pointand we will use many of these reserved words in our programs laterso it will become quite natural to not use them as variable names howeverfor programming physics and mathematicsit could be worth noting lambdasince the greek letter is common in physics and mathematics formulas since python does not understand greek lettersit is common to just spell them out when programming formulathat isa becomes alphaand so on howeverusing this approach for will lead to an errorand the error message might not be very easy to understand the problem is easily solved by introducing small intentional typo and writing lmbda or similar integer division can cause surprising errors in python and many other programming languagesunintended integer division can sometimes cause surprising results in python this is no longer problemso you are not likely to run into it during this coursebut it is worth being aware ofsince many other programming languages behave in this way recall from above that various operations behave differentlydepending on the type of the variable they work onsuch as in adding two strings versus adding numbers in python the division operator/behaves as in normal division if one of the two arguments is floatbutif both are integers then it will perform integer division and discard the decimal portion of the result consider the following interactive sessionwhich runs python
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 could be good habit to ensure that variables used in calculations are actually floatsby simply defining them as rather than although it does not really make difference in python it is good to get into this habit simply to avoid problems when programming in other languages later 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,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 used to automate repetitive and tedious operations loops are used in most computer programsand they look very similar across wide range of programming languages we will primarily use loops for calculationsbut as you gain more experienceyou will be able to automate other repetitive tasks two types of loops will be introduced in this the while loop and the for loop both will be used extensively in all subsequent in addition to the loop conceptwe will introduce boolean expressionswhich are expressions with true/false valueand new variable type called listwhich is used to store sequences of data loops for automating repetitive tasks to start with motivating exampleconsider again the simple interest calculation formulaa ( ( / )) in we implemented this formula as single-line python programbut what if we want to generate table showing how the invested amount grows with the yearsfor instancewe could write and in two columns like this (cthe author( sundnesintroduction to scientific programming with pythonsimula springerbriefs on computing
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 obviously not very good solutionsince it is very boring to write and errors are easily introduced in the code as general rulewhen programming becomes repetitive and boringthere is usually better way of solving the problem at hand in this casewe will utilize one of the main strengths of computerstheir strong ability to perform large numbers of simple and repetitive tasks for this purposewe use loops the most general loop in python is called while loop while loop will repeatedly execute set of statements as long as given condition is satisfied the syntax of the while loop looks like the followingwhile conditionthe condition here is python expression that is evaluated as either true or falsewhichin computer science termsis called boolean expression notice also the indentation of all the statements that belong inside the loop indentation is the way python groups code together in blocks in loop such as this oneall the lines we want to be repeated inside the loop must be indentedwith exactly the same indentation the loop ends when an unindented statement is encountered to make things bit more concretelet us use write while loop to produce the investment growth table above more preciselythe task we want to solve is the followinggiven range of years from zero to in steps of one yearcalculate the corresponding amount and print both values to the screen to write the correct while loop for solving given taskwe need to answer four key questions(iwhere/how does the loop startthat iswhat are the initial values of the variables(iiwhich statements should be repeated inside the loop(iiiwhen does the loop stopthat iswhat condition should become false to make the loop stopand (ivhow should variables be updated for each
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 condition becomes something like < and (ivwe want to print the values for steps of one yearso we need to increase by one for every pass of the loop inserting these details into the general while loop framework above yields the following codep while < ( + / )** print(nan loop heading with condition st statement inside loop nd statement inside loop last statement inside loop the flow of this program is as follows firstn is < is truetherefore we enter the loop and execute the loop statementscompute print and update to when we have reached the last line inside the loopwe return to the while line and evaluate < again this condition is still trueand the loop statements are therefore executed again new is computed and printedand is updated to the value of two we continue this way until is updated from to nowwhen we return to evaluate < the condition is false the program then jumps straight to the first line after the loopand the loop is finished useful tipa very common mistake in while loops is to forget to update the variables inside the loopin this case forgetting the line this error will lead to an infinite loopwhich will keep printing the same line forever if you run the program from the terminal window it can be stopped with ctrl+cso you can correct the mistake and re-run the program boolean expressions an expression with value of true or false is called boolean expression boolean expressions are essential in while loops and other important programming constructsand they exist in most modern programming languages we have seen few examples alreadyincluding comparisons such as = in
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 mathematicssince it is used to assign value to variable checking two variables for equality is different operationand to distinguish it from assignmentwe use =we can output the value of boolean expressions with statements such as print( < or in an interactive python shellas followsc ! true false = true most of the boolean expressions we will use in this course are of the simple kind aboveconsisting of single comparison that should be familiar from mathematics howeverwe can combine multiple conditions using and/or to construct while loops such as thesewhile condition and condition while condition or condition the rules for evaluating such compound expressions are as expectedc and is true if both and are truewhile or is true if at least one of the two conditions and is true one can also negate boolean expression using the term notwhich simply yields that not is true if is falseand vice versa to gain feel for compound boolean expressionsyou can go through the following examples by hand and predict the outcomeand then try to run the code to obtain the resultx print( > and print( > or print( or print( or not print(- < same as - and < print(not ( or )
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 interactive python shell using lists to store sequences of data so farwe have used one variable to refer to one number (or stringsometimes we naturally have collection of numberssuch as the -values (years created in the example above in some casessuch as the one abovewe are simply interested in writing all the values to the screenin which case using single variable that is updated and printed for each pass of the loop works fine howeversometimes we want to store sequence of such variablesfor instanceto process them further elsewhere in the program we couldof courseuse separate variable for each value of nas followsn howeverthis is another example of programming that becomes extremely repetitive and boringand there is obviously better solution in pythonthe most flexible way to store such sequence of variables is to use listn [ notice the square brackets and the commas separating the valueswhich is how we tell python that is list variable now we have single variable that can hold all the values we want python lists are not reserved just for numbers and can hold any kind of objectand even different kinds of objects they also have great deal of convenient built-in functionalitywhich makes them very flexible and useful and extremely popular in python programs we will not cover all the aspects of lists and list operations in this bookbut we will use some of the more basic ones we have already seen how to initialize list using square brackets and comma-separated valuessuch as [- ' string' to retrieve individual elements from the listwe can use an indexfor instance [ will pick out the element with index that isthe fourth element (having value of zeroin the listsince the numbering starts at zero list indices start at zero and run to the where is the number of elements in the list
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 operations allow usfor instanceto append an element to listadd two lists togethercheck if list contains given elementand delete an element from listn [ append( add new element at the end print(nn [ extend at the end print(nprint( in #is the value found in ntrue/false del [ #remove the first item from the list these list operationsin particular those to initializeappend toand index listare extremely common in python programsand will be used throughout this book it is good idea to spend some time making sure you fully understand how they work it is also worth noting one important difference between lists and the simpler variable types we introduced in for instancetwo statementssuch as would create two integer variablesboth having value but they are not the same variable the second statement = will create copy of and assign it to band if we later change ba will not be affected with liststhe situation is differentas illustrated by the following examplel[ [ , , , [- [ hereboth and are listsand when changes also changes this happens because assigning list to new variable does not copy the original listbut instead creates reference to the same list so and arein this casejust two variables pointing to the exact same list if we actually want to create copy of the original listwe need to state this explicitly with copy(
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 in listthe key line is the first onewhich will simply run through the listelement by element for each pass of the loopthe single element is stored in the variable elementand the block of code inside the for loop typically involves calculations using this element variable when the code lines in this block are completedthe loop moves on to the next element in the listand continues in this manner until there are no more elements in the list it is easy to see why this loop is simpler than the while loopsince no condition is needed to stop the loop and there is no need to update variable inside the loop the for loop will simply iterate over all the elements in predefined listand stop when there are no more elements on the other handthe for loop is slightly less flexiblesince the list needs to predefined the for loop is the best choice in most cases in which we know in advance how many times we want to perform set of operations in cases in which this number is not knownthe while loop is usually the best choice for concrete for loop examplewe return to the investment growth example introduced above to write for loop for given tasktwo key questions must be answered(iwhat should the list containand (iiwhat operations should be performed on the elements in the listin the present casethe natural answers are (ithe list should be range of -values from zero to in steps of and (iithe operations to be repeated are the computation of and the printing of the two valuesessentially the same as in the while loop the full program using for loop thus becomes years [ for in yearsa ( + / )** print(naas with the while loopthe statements inside the loop must be indented simply by counting the lines of code in the two programs shows that the for loop is somewhat simpler and quicker to write than the while loop most people will argue that the overall structure of the program is also simpler and less error-pronewith no need to check criterion to stop the loop or to
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 the way we defined the list years in the code above is not very scalable to long listsand quickly becomes repetitive and boring as stated abovewhen programming become repetitive and boringa better solution usually exists such is the case hereand very rarely do values in list need to be filled explicitlyas done here better alternatives include built-in python function called rangeoften in combination with for loop or so-called list comprehension we will return to these tools later in the when running the codeone can also observe that the two columns of degrees values are not perfectly alignedsince print always uses the minimum amount of space to output the numbers if we want the output in two nicely aligned columnsthis is easily achieved by using the -string formatting we introduced in the previous the resulting code can look like thisyears [ for in yearsr ( + / )** print( '{ : }{ : }'output is now nicely aligned for loop can always be translated to while loop as described abovea while loop is more flexible than for loop for loop can always be transformed into while loopbut not all while loops can be expressed as for loops for loop always traverses traverses listcarries out some processing on each elementand stops when it reaches the last one this behavior is easy to mimic in while loop using list indexing and the len functionwhich were both introduced above for loop of the form for element in somelistprocess element translates to the following while loopindex while index len(somelist)element somelist[indexprocess element index +
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 use built-in python function named rangewhich returns list of integers for in range( + ) ( + / )** print( ,ahere we used range with single argument which will generate list of integers from zero to (not including we can also use range with two or three arguments the most general case range(startstopincgenerates list of integers startstart+incstart+ *incand so on up tobut not includingstop when used with just single argumentas abovethis argument is treated as the stop valueand range(stopis short for range( stop with two argumentsthe interpretation is range(start,stop)short for range(start,stop, this behaviorwhere single function can be used with different numbers of argumentsis common both in python and many other programming languagesand makes the use of such functions very flexible and efficient if we want the most common behaviorwe need only provide single argument and the others are automatically set to default valueshoweverif we want something differentwe can do so easily by including more arguments we will use the range function in combination with for loops extensively through this bookand it is good idea to spend some time becoming familiar with it good way to gain feel for how the range-function works is to test statements such as print(list(range(start,stop,inc))in an interactive python shellfor different argument values filling list with values using for loop one motivation for introducing lists is to conveniently store sequence of numbers as single variablefor instancefor processing later in the program howeverin the code abovewe did not really utilize thissince all we did was print the numbers to the screenand the only list we created was simple sequence from zero to it could be more useful to store the amounts in listwhich can be easily be achieved with for loop the following code illustrates very common way to fill lists with values in python in python range does not technically produce listbut list-like object called an iterator in terms of use in for loopwhich is the most common use of rangethere is no practical difference between list and an iterator howeverif we tryfor instanceprint(range( )the output does not look like list to obtain output that looks like listwhich can be useful for debuggingthe iterator must be converted to an actual listprint(list(range( ))
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 simple way of creating list and filling it with values is very common in python programs mathematical sums are implemented as for loops very common example of repetitive task in mathematics is the computation of sumfor instancen si = for large values of such sums are tedious to calculate by handbut they are very easy to program using range and for loopn for in range( + ) + ** notice the structure of this codewhich is quite similar to the way we filled list with values in the previous example firstwe initialize the summation variable (sto zeroand then the terms of the sum are added one by one for each iteration of the for loop the example shown here illustrates the standard recipe for implementing mathematical sumswhich are common in scientific programming and appear frequently in this book it is worthwhile spending some time to fully understand and remember how such sums is implemented how can we change the elements in listin some cases we want to change elements in list consider first simple example where we have list of numbersand want to add the value of two to all the numbers following the ideas introduced abovea natural approach is to use for loop to traverse the listas followsv [- for in ve print( [- unaltered!
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 (intvariableand it is in fact copy of each element in the listand not the actual element thereforewhen we change ewe change only the copy and not the actual list element the copy is overwritten in the next pass of the loop anywaysoin this caseall the numbers that are incremented by two are simply lost the solution is to access the actual elements by indexing into the listv [- for in range(len( )) [iv[ print( [ notice in particular the use of range(len( ))which is common construction in python programs it creates set of integers running from zero to len( )- that can be iterated over with the for loop and used to loop through all the elements in the list list comprehensions for compact creation of lists abovewe introduced one common way of constructing listswhich is to start with an empty list and use for loop to fill it with values we can extend this example to fill several lists in one loopfor instanceif we want to examine the effect of low and high interest rates on our bank deposit we start with two empty lists and fill both with values in the same loopp r_low r_high a_high [a_low [for in range( + )a_low append( *( +r_low/ )**na_high append( *( +r_high/ )**nthis approach to using for loop to fill list with values is so common in python that compact construct has been introducedcalled list comprehension the code in the previous example can be replaced by the followingp r_low r_high a_low [ *( +r_low/ )** for in range( + )a_high [ *( +r_high/ )** for in range( + )
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 list are usually easy to understand from the code inside the brackets the general form of list comprehension looks like newlist [expression for element in somelistwhere expression typically involves element the list comprehension works exactly like for loopit runs through all the elements in someliststores copy of each element in the variable elementevaluates expressionand appends the result to the list newlist the resulting list newlist will have the same length as somelistand its elements are given by expression list comprehensions are important to know aboutsince you will see them frequently when reading python code written by others they are convenient to use for the programming tasks covered in this bookbut not strictly necessarysince the same thing can always be accomplished with regular for loop traversing multiple lists simultaneously with zip sometimes we want to loop over two lists at the same time for instanceconsider printing out the contents of the a_low and a_high lists of the example above we can accomplish this using range and list indexingas in for in range(len(a_low))print(a_low[ ]a_high[ ]howevera built-in python function named zip provides an alternative solutionwhich many consider more elegant and "pythonic"for lowhigh in zip(a_lowa_high)print(lowhighthe output is exactly the samebut the use of zip makes the for loop more similar to the way we traverse single list we run through both listsextract the elements from each one into the variables low and highand use these variables inside the loopas we are used to we can also use zip with three listsl [ ] [ ]for in zip( )print( [ lists traversed with zip typically have the same lengthbut the function also works for lists of different lengths in this casethe for loop will simply stop when it reaches the end of the shortest listand the remaining elements of the longer lists are not visited
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 together in new lista_low [ *( +)** for in range( )a_high [ *( +)** for in range( )amounts [a_lowa_highlist of two lists print(amounts[ ]the a_low list print(amounts[ ]the a_high list print(amounts[ ][ ]the rd element in a_high the indexing of nested lists illustrated here is quite logicalbut can take some time getting used to the important thing is thatif amounts is list containing liststhenfor instanceamounts[ is also list and can be indexed in the way we are used to indexing into this list is done in the usual waysuch thatfor instanceamounts[ ][ is the first element of the first list contained in amounts playing bit with indexing nested lists in the interactive python shell is useful exercise to understand how they are used iterating over nested lists also works as expected considerfor instancethe following code for sublist in somelistfor sublist in sublist for value in sublist work with value heresomelist is three-dimensional nested listthat isits elements are listswhichin turncontain lists the resulting nested for loop looks bit complicatedbut it follows exactly the same logic as the simpler for loops used above when the outer loop startsthe first element from somelist is copied into the variable sublist and then we then enter the code block inside the loopwhich is new for loop that will start traversing sublist that isfirst copying the first element into the variable sublist then the process is repeatedwith the innermost loop traversing all the elements of sublist copying each element into the variable valueand doing some calculations with this variable when it reaches the end of sublist the innermost for loop is overwe "move outwardone level in terms of the loopsto the loop for sublist in sublistwhich moves to the next element and starts new run through the innermost loop similar iterations over nested loops can be obtained by looping over the list indicesas followsfor in range(len(somelist))for in range(len(somelist[ ]))
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 some examples of small nested lists in python shell or small python programand examine the results of indexing and looping over the lists the following code is one such example try to step through this program by hand and predict the output before running the code and checking the resultl [[ ][- ]for row in lfor column in rowprint(columnlist slicing is used to extract parts of list we have seen how we can index list to extract single elementbut sometimes it is useful to capture parts of listfor instanceall the elements from an index to an index python offers list slicing for such tasks for list awe have seen that single element is extracted with [ ]where is an integerbut we can also use the more general syntax [start:stop:stepto extract slice of the arguments resemble those of the range functionand such list slicing will extract all elements starting from index start up to but not including stopwith step step as for the range functionwe can omit some of the arguments and rely on default values the following examples illustrate the use of slicinga [ [ :from index to end of list [ [ : [ from index up tobut not incl index [: from start up tobut not incl index [ [ :- from index to next last element [ [:the whole list [ note that these sublists (slicesare copies of the original list statement such asfor instanceb [:will make copy of the entire list aand any subsequent changes to will not change as for the nested lists considered abovea good way to become familiar with list slicing is to create small
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 work mostly with lists of one or two dimensions ( nonnested lists or the simplest lists-of-lists tuples lists are flexible and user-friendly way to store sequences of numbersand are used in nearly all python programs howevera few other data types are also made to store sequences of data one of the most important ones is called tupleand it is essentially constant list that cannot be changed tuple is defined in almost the same way as listbut with normal parentheses instead of the square brackets alternativelywe can skip the parentheses and just use comma-separated sequence of values to define tuple the following are two examples that are entirely equivalent and define the same tupledefine tuple can skip parentheses ( 'temp pdf' 'temp pdftuples also provide much of the same functionality as listsincluding indexing and and slicingt (- - ( 'temp pdf'- - [ [ :( 'temp pdf'- - in true add two tuples indexing subtuple/slice membership howevertuples are immutablewhich means that they cannot be changed thereforesome operations we are used to from lists will not work continuing the interactive session from abovethe following are some examples of illegal tuple operationst[ - typeerror'tupleobject does not support item assignment append( attributeerror'tupleobject has no attribute 'appenddel [
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 assignment works by first evaluating the expression on the right hand sidewhich in this example means to add two tuples together the result is new tupleand neither nor (- are changed in the process thenthe new tuple is assigned to the variable tmeaning that the original tuple is replaced by the new and longer tuple the tuple itself is never changedbut the contents of the variable is replaced with new one natural question to askthenis why do we need tuples at allwhen lists can do the same job and are much more flexiblethe main reason for this is thatin many casesit is convenient to work on item that is constantsince it is protected against accidental changes and can be used as key in so-called dictionariesan important python datastructure that will be introduced in throughout this bookwe will not do much explicit programming with tuplesbut we will run into them as part of the modules we import and useso it is important to know what they are 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,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 the kind ( and so on similar function concept exists in programmingwhere function is piece of code that takes one or more variables as inputcarries out some operations using these variablesand produces output in return the function concept in programming is more general than in mathematicsand is not restricted to numbers or mathematical expressionsbut the general idea is exactly the same branchingor if-testsis another fundamental concept that exists in all common programming languages the idea is that decisions are made in the code based on the value of some boolean expression or variable if the expression evaluates to trueone set of operations is performedand if the expression is falsea different set of operations is such tests are essential for controlling the flow of computer program programming with functions we have already used number of python functions in the previous the mathematical functions from the math module are essentially the same as we are used to from mathematics or from pushing buttons on calculatorfrom math import sin( )*log(xadditionallywe used few non-mathematical functionssuch as len and range len(somelistfor in range( )(cthe author( sundnesintroduction to scientific programming with pythonsimula springerbriefs on computing
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 functions are also referred to as methodsand will be considered in more detail in in the present we will primarily consider regularunboundfunctions in pythonsuch functions provide easy access to already existing program code written by others ( sin( )there is plenty of such code in pythonand nearly all programs involve importing one or more modules and using pre-defined functions from them one advantage of functions is that we can use them without knowing anything about how they are implemented all we need to know is what goes in and what comes outand the function can thus be used as black box functions also provide way of reusing code we have written ourselveseither in previous projects or as part of the current codeand this is the main focus of this functions let us delegate responsibilities and split program into smaller taskswhich is essential for solving all problems of some complexity as we shall see later in this splitting program into smaller functions is also convenient for testing and verifying that program works as it should we can write small pieces of code that test individual functions and ensure that they work correctly before putting the functions together into complete program if such tests are done properlywe can have some confidence that our main program works as expected we will return to this topic towards the end of the so how do we write function in pythonstarting with simple exampleconsider the previously considered mathematical function (np ( / ) for given values and we can implement this in python as followsdef amount( ) return *( + / )** these two lines of code are very similar to the examples from but they contain few new concepts that are worth noting starting with the first linedef amount( )is called the function headerand defines the function' interface all function definitions in python start with the word defwhich is simply how we tell python that the following code defines function after def comes the name of the functionfollowed by parentheses containing
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 parentheses empty the lines following the function header are the function bodywhich need to be indented the indentation serves the same purpose as for the loops in to specify which lines of code belong inside the functionor to the function body the two first lines of the function body are regular assignmentsbut since they occur inside functionthey define local variables and local variables the argument are used inside the function just as regular variables we will return to this topic in more detail later the last line of the function body starts with the keyword returnwhich is also new in this and is used to specify the output returned by the function it is important not to confuse this return statement with the print statements we used previously the use of print will simply output something to the screenwhile return makes the function provide an outputwhich can be thought of as variable being passed back to the code that called the function consider for instance the example len(somelistused in the previous where len returned an integer that was assigned to variable another important thing to note about the code above is that it does not do much in facta function definition does essentially nothing before it is called the analogue to the function definition in mathematics is to simply write down function (xas mathematical expression this defines the functionbut there is no output until we start evaluating the function for some specific values of in programmingwe say that we call the function when we use it when programming with functionsit is common to refer to the main program as basically every line of code that is not inside function when running the programonly the statements in the main program are executed code inside function definitions is not run until we include call to the function in the main program we have already called pre-defined functions like sinlenetcin previous and function we have written ourselves is called in exactly the same waydef amount( ) return *( + / )** year amount(year amount( call call this is not entirely truesince defining the function creates function objectwhich we can see by defining dummy function in the python shell and then calling dir(to obtain list of defined variables howeverno visible output is produced until we actually call the functionand forgetting to call the function is common mistake when starting to program with functions
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 other programming languagespython does not require the type of function arguments to be specified judging from the function header onlythe argument of amount(nabove could be any kind of variable howeverby looking at how is used inside the functionwe can tell that it must be number (integer or floatif we write complex functions where the argument types are not obviouswe can insert comment immediately after the headera so-called doc stringto tell users what the arguments should be we will return to the topic of doc strings later in this function arguments and local variables just as in mathematicswe can define python functions with more than one argument the formula above involves both and in addition to nand including them all as arguments could be useful the function definition could then look like def amount(prn)return *( + / )** sample callsa amount( amount( = amount( = note that we are using the arguments prand inside the function exactly as in the previous examplewhere we defined and inside the function inside functionthere is no distinction between such local variables and the arguments passed to the function the arguments also become local variablesand are used in exactly the same way as any variable we define inside the function howeverthere is an important distinction between local and global variables variables defined in the main program become global variableswhereas variables defined inside functions are local the local variables are only defined and available inside functionwhereas global variables can be used everywhere in program if we tried to access pror ( by print( )from outside the functionwe will simply obtain an error message stating that the variable is not defined arguments can be positional arguments or keyword arguments notice also the alternative ways of calling function we can either specify the
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 they are assigned arguments that are passed including the name are called keyword arguments keyword arguments need to match the definition of the functionthat iscalling the function above with amount( year= would cause an error message because year is not defined as an argument to the function another rule worth noting is that positional argument cannot follow keyword argumenta call such as amount( = is finebut amount( = is not and the program will stop with an error message this rule is quite logicalsince random mix of positional and keyword arguments would make the call very confusing the difference between local and global variables the distinction between local and global variables is generally important in programmingand can be confusing at first as stated abovethe arguments passed to functionas well as variables we define inside the functionbecome local variables these variables behave exactly as we are used to inside the functionbut are not visible outside it the potential source of confusion is that global variables are also accessible inside functionjust as everywhere else in the code we could have assigned value to the variables and outside the functionanywhere before the first call to amountand the code would still workp def amount( )return *( + / )** print(amount( )here is passed as an argumentwhilefor and rthe values assigned outside the function is used howeverit is also possible to define local and global variables with the same namesuch as def amount( ) return *( + / )** which value of is used in the function call herelocal variable names always take precedence over the global names when the mathematical formula is encountered in the code abovepython will look for the values of the variables prand that appear in the formula firstthe so-called local namespace is searchedthat ispython looks for local variables with the given names if
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 isit has been defined in the main programthen the corresponding value is used if no global variable with the right name is found there are no more places to searchand the program ends with an error message this sequential search for variables is quite natural and logicalbut still potential source of confusion and programming errors additional confusion can arise if we attempt to change global variable inside function considerfor instancethis small extension of the code abovep def amount( ) return *( + / )** print(amount( = )print( as revealed by the print statementsr is set to inside the functionbut the global variable remains unchanged after the function has been called since the line occurs inside functionpython will treat this as the definition of new local variablerather than trying to change global one we thus define new local with value while there is still another defined in the global namespace after the function has endedthe local variable no longer exists (in programming termsit goes out of scope)whereas the global is still there and has its original value if we actually want to change global variable inside functionwe must explicitly state so by using the keyword global consider this minor change of the code abovep def amount( )global return *( + / )** print(amount( = )print(
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 to the function to the function similarlyif we want the function to change global variable then we should make the function return this variableinstead of using the keyword global it is difficult to think of single example where using global is the best solutionand in practice it should never be used if we actually wanted the function above to change the global rthe following is better wayp def amount( , ) *( + / )** return ar amount( print( rnotice thatherewe return two values from the functionseparated by commajust as in the list of argumentsand we also assign the returned values to the global variables in the line where the function is called although this simple example might not be the most useful in practicethere are many cases in which it is useful for function call to change global variable in such cases the change should always be performed in this wayby passing the global variable in as an argumentreturning the variable from the functionand then assigning the returned value to the global variable following these steps is far better than using the global keyword inside the functionsince it ensures that each function is self-contained entitywith clearly defined interface to the rest of the code through the list of arguments and return values multiple return values are returned as tuple for more practically relevant example of multiple return valuessay we want to implement mathematical function so that both the function value and its derivative are returned considerfor instancethe simple physics formula that describes the height of an object in vertical motiony(tv ( / )gt where is the initial velocityg is the gravitational constantand is time the derivative of the function is (tv -gtand we can implement python function that returns both the function value and the derivativedef yfunc(tv ) * * * ** dydt * return ydydt
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 we could therefore replace the call above with something like the followingpos_vel yfunc( , print(pos_velprint(type(pos_vel)( - we see that the function returns tuple with two elements in the previous callwhen we included comma-separated list of variable names on the lefthand side ( positionvelocity)python would unpack the elements in the tuple into the corresponding variables for this unpacking to workthe number of variables must match the length of the tupleotherwisewe obtain an error message stating that there are too many or not enough values to unpack function can return any number of argumentsseparated by commas exactly as above here we have threedef ( )return xx** ** ( print(type( )sxx notice the last linewhere tuple of length is unpacked into three individual variables examplea function to compute sum for more relevant function exampleof kind that will arise frequently in this bookconsider the sum (xnn xi = which is an approximation to ln( xfor finite and | the corresponding python function for (xnlooks like def ( , ) for in range( , + ) + ** / return
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)in addition to the value of the sumfrom math import log def (xn) for in range( , + ) + ** / value_of_sum error -log( -xvalue_of_sum return value_of_sumerror typical callx valueerror (xna function does not need return statement all the functions considered so far have included return statement while this will be the case for most of the functions we write in this coursethere will be exceptionsand function does not need to have return statement for instancesome functions only serve the purpose of printing information to the screenas in def somefunc(obj)print(objreturn_value somefunc( herethe last line does not make much sensealthough it is actually valid python code and will run without errors if somefunc does not return anythinghow can we then call the function and assign the result to variableif we do not include return statement in functionpython will automatically return variable with value none the value of the variable return_value in this case will therefore be nonewhich is not very usefulbut serves to illustrate the behavior of function with no return statement most functions we will write in this course will either return variables or print or plot something to the screen one typical use of function without return value is to print information in tabular format to the screen this is useful in many contextsincluding studying the convergence of series approximations such as the one above the following function calls the ( ,nfunction defined aboveand uses for loop to print relevant information in nicely formatted table
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 default arguments and doc strings when we used the range-function in the previous we saw that we could vary the number of arguments in the function call from one to threeand the non-specified arguments would be assigned default values we can achieve the same functionality in our own functionsby defining default arguments in the function definitiondef somefunc(arg arg kwarg =truekwarg = )print(arg arg kwarg kwarg function defined in this way can be called with twothreeor four arguments the first two have no default value and must therefore be included in the callwhile the last two are optional and will be set to the default value if not specified in the call in texts on python programmingdefault arguments are often referred to as keyword argumentsalthough these terms do not mean exactly the same thing they arehoweverclosely relatedwhich is why the terms are sometimes used interchangeably just as we cannot have keyword arguments preceding positional arguments in function callwe cannot have default arguments preceding non-default arguments in the function header the following code demonstrates uses of the alternative function calls for useless but illustrative function testing simple function such as the followingwhich does nothing but print out the argument valuesis good way to understand the implications of default arguments and the resulting flexibility in argument listsdef somefunc(arg arg kwarg =truekwarg = )print(arg arg kwarg kwarg somefunc('hello'[ , ]drop kwarg and kwarg
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 now know about default argumentswe can improve the function considered abovewhich implements the formula (tv gt hereit could be natural to think of as the primary argument to the functionwhich should always be providedwhile and possibly also could be provided as default arguments the function definition in python could read def yfunc(tv = = ) * * * ** dydt * return ydydt #example callsy dy yfunc( dy yfunc( , = dy yfunc( , , documentation of python functions an important python convention is to document the purpose of functionits argumentsand its return values in doc string (triple-quotedstring written immediately after the function header the doc string can be long or shortdepending on the complexity of the function and its inputs and outputs the following two examples show how doc string can be useddef amount(prn)"""compute the growth of an investment over time "" *( + / )** return def line( )""compute the coefficients and in the mathematical expression for straight line * that goes through two points ( and ( point on the line (floats
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 automatically generating nicely formatted software documentation much of the online documentation of python libraries and modules is automatically generated from doc strings included in the code if-tests for branching the program flow in computer programs we often want to perform different actions depending on condition as usualwe can find similar concept in mathematics that should be familiar to most readers of this book consider function defined in piecewise mannerfor instancesin < < ( otherwise the python implementation of such function needs to test the value of the input xand return either zero or sin(xdepending on the outcome such decision in the program code is called branching and is obtained using an if-testormore generallyan if-else block the code looks like from math import sinpi def ( )if < <pireturn sin(xelsereturn print( ( )print( ( *pi)the new item here is the if-else block an if-test is simply constructed by the keyword if followed by boolean variable or expressionand then block of code which is to be executed if the condition is true when the iftest is reached in the function abovethe boolean condition is testedjust as for the while loops in the previous if the condition is truethe following block of indented code is executed (in this casejust one line)if notthe indented code block after else is executed you might also notice
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 return statements unless they are combined with if-testssinceif the first one is always executed the others will never be reached sometimes we just want piece of code to be executed if condition is trueand to do nothing otherwise in such caseswe can skip the else block and define only an if-testif conditionherewhatever is inside the if-block is executed if condition is trueotherwise the program simply moves to the next line after the block as abovewe can add an else-block to ensure that exactly one of two code blocks is executed if conditionelsefor mathematical functions of the form considered above we usually want to include an else-blocksince we want the function to return meaningful value for all input arguments forgetting the else-block in the definition (xabove would make the function return sin( ( floatfor < <pand otherwise nonewhich is obviously not what we want finallywe cans combine multiple if-else statements with different conditions if condition elif condition elif condition elsenotice the keyword elifshort for else ifwhich ensures that that subsequent conditions are only tested only if the preceding ones are false the conditions are checked one by one andas soon as one is evaluated as truethe corresponding block is executed and the program moves to the first statement after the else block the remaining conditions are not checked if none of the conditions is truethe code inside the else block is executed multiple branching has useful applications in mathematicssince we often see piecewise functions defined on multiple intervals consider for instance the piecewise linear function
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 shorter code the list comprehensions in offered more compact alternative to the standard way of defining listsand similar alternative exists for if-tests common use of if-else blocks is to assign value to variablewhere the value depends on some conditionjust as in the examples above the general form looks like if conditionvariable value elsevariable value this code can be replaced by the following one-line if-else blockvariable (value if condition else value using this compact notationwe can write the example from the start of this section as def ( )return (sin(xif < <pi else functions as arguments to functions arguments to python functions can be any python objectincluding another function this functionality is quite useful for many scientific applicationswhere we need to define mathematical functions that operate on or make use of other mathematical functions for instancewe can easily write python functions for numerical approximations of integrals ( )dxderivatives ( )and roots ( for such functions to be general and usefulthey
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( + ))/float( *hreturn we see that the function is passed to the function just as any other argumentand is called as regular function inside diff of coursefor this to workwe need to actually send callable function as the first argument to diff if we send something elselike number or stringthe code will stop with an error when it tries to make the call ( -hin the next line such potential errors are part of the price we pay for python' flexibility we can pass any argument to functionbut the object we pass must be possible to use as intended inside the function as noted abovefor more complex functionsit is useful to include doc string that specifies the types of arguments the function expects lambda functions for compact inline function definitions in order to use the function diff aboveone would standardly define our (xas python functionand then pass it as an argument to diff the following code shows an exampledef ( )return ** df diff ( , print(df the concept known as lambda function offers compact way to define functionswhich can be convenient for the present application using the keyword lambdawe can define our on single lineas followsf lambda xx** more generallya lambda function defined by somefunc lambda some_expression is equivalent to def somefunc( )return some_expression it could be natural to ask whether anything is really gained hereand whether it is useful to introduce new concept just to reduce function definition
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(df using lambda functions in this way can be quite convenient in cases in which we need to pass simple mathematical expression as an argument to python function we save some typingand could also improve the code' readability solving equations with python functions solving equations of the form ( is frequently occuring task in all branches of science and engineering for special casessuch as linear or quadratic we have simple formulas that give us the solution directly in the general casehoweverthe equation cannot be solved analyticallyand we need to find an approximate solution using numerical methods we shall see that we can create powerful and flexible tools for equation solving based on the building blocks introduced so far specificallywe will combine functions and function arguments with the while loop introduced in finding roots on an interval with the bisection method one of the simplest algorithms for solving equations of the form ( is called the bisection method this method is founded on the intermediate value theoremwhich states thatif continuous function changes sign on an interval [abthen there must be value [absuch that ( in the bisection method we start by choosing an interval [abon which changes sign ( ( ) ( )and then compute the midpoint ( )/ and check the sign of (mif changes sign on [amthen we repeat the process on the interval [am]otherwisewe choose [mbas our new interval and repeat the process there these steps are conveniently implemented as while loopand we can create generic tool by placing the while loop inside function that takes function as argumentfrom math import exp def bisection( , , ,tol - )if ( )* ( print( 'no roots or more than one root in [{ },{ }]'return ( + )/ while abs( ( )tolif ( )* (
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 tolerance for the approximate solution the first if-test of the function simply checks that changes sign in [ab]which ensures that the function has at least one root on the interval we then proceed to define the midpoint and enter the while-loopwhich forms the core of the algorithm this loop will continue running as long as abs( ( )tol (otherwise is our solution)repeatedly checking whether changes sign on [amor [mb]and then calculating new to repeat the process on an interval of half the size newton' method gives faster convergence the bisection method converges quite slowlyand other methods are far more popular for solving nonlinear equations in particularnumerous varieties of newton' method are widely used in practice newton' method is based on local linearization of the non-linear function (xstarting with an initial guess we replaces (xby linear function (xthat satisfies (xf (xin small interval around thenwe solve the equation ( to find an updated guess and repeat the process of linearization around that point repeated application of these steps converges quickly towards the true solutionprovided that the initial guess is sufficiently close in mathematicsone step of the algorithm looks like (xn xn+ xn (xn where xn is the solution after iterationsxn+ is the improved approximationand (xn is the derivative of in xn just as the bisection methodnewton' method is easy to implement in while loopand we can implement it as generic function that takes python function implementing (xas argument the function will also need ( )since this is used in the algorithmas well as an initial guess and tolerancefrom math import exp def newton(fdfdxx tol - ) ( while abs( tol
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 compute the next oneso for each iteration we update to hold the most recent approximationand then use this to compute the next one note also that the implementation provided here is not very robustand if the method does not convergeit will simply continue in an infinite loop one simple way to improve the implementation is to stop the method after given number of iterationsfrom math import exp def newton (fdfdxx max_it= tol - ) ( iter while abs( tol and iter max_itx /dfdx( ( iter + converged iter max_it return convergediter #call the method for ( ) ** - * +exp(-xf lambda xx** - * +exp(-xdfdx lambda * - -exp(-xsolconvergediter newton ( ,dfdx, ,tol= - if convergedprint( 'newtons method converged in {iteriterations'elseprint( 'the method did not converge'newton' method usually converges much faster than the bisection methodbut has the disadvantage the function needs to be manually differentiated in we will see some examples of how this step can be avoided
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 earlyand can build our program from components that are known to work the process is often referred to as unit testingsince each test verifies that small unit of the program works as expected many programmers even take the approach one step further and write the test before they write the actual function this approach is often referred to as test-driven development and is an increasingly popular method for software development the tests we write to test our functions are also functionsa special type of function known as test functions writing good test functionswhich test the functionality of our code in reliable mannercan be quite challenginghoweverthe overall idea of test functions is very simple for given functionwhich often takes one or more argumentswe choose arguments such that we can calculate the result of the function by hand inside the test functionwe then simply call our function with the right arguments and compare the result returned by the function with the expected (hand-calculatedresult the following example illustrates how we can write test function to test that the (verysimple function double(xworks as it shoulddef double( )return * some function def test_double()associated test function some chosen value expected expected result from double(xcomputed double(xsuccess computed =expected boolean valuetest passedmsg 'computed {computed}expected {expected}assert successmsg in this codethe only python keyword that we have not seen previously is assertwhich is used instead of return whenever we write test function test functions should not return anythingso regular return statement would not make sense the only purpose of the test function is to compare the value returned by function with the value we expect it to returnand to write an error message if the two are different this task is precisely what assert does the keyword assert should always be followed by conditionsuccess in the code abovethat is true if the test passes and false if it fails the code above follows the typical recipewe compare the expected with the returned result in computed =expectedwhich is boolean expression returning true or false this value is then assigned to the variable successwhich is included in the assert statement the last part of the
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 about what actually went wrong some rules should be observed when writing test functionsthe test function must have at least one statement of the type assert successwhere success is boolean variable or expressionwhich is true if the test passed and false otherwise we can include more than one assert statement if we wantbut we always need at least one the test function should take no arguments the function to be tested will typically be called with one or more argumentsbut these should be defined as local variables inside the test function the name of the function should always be test_followed by the name of the function we want to test following this convention is useful because it makes it obvious to anyone reading the code that the function is test functionand it is also used by tools that can automatically run all test functions in given file or directory more about this is discussed below if we follow these rulesand remember the fundamental idea that test function simply compares the returned result with the expected resultwriting test functions does not have to be complicated in particularmany of the functions we write in this course will evaluate some kind of mathematical function and then return either number or list/tuple of numbers for this type of functionthe recipe for test functions is quite rigidand the structure is usually exactly the same as in the simple example above if you are new to programmingit can be confusing to be faced with general task such as "write test function for the python function somefunc( , ),and it is natural to ask questions about what arguments the function should be tested for and how you can know what the expected values are in such cases it is important to remember the overall idea of test functionsand also that these are choices that must be made by the programmer you have to choose set of suitable argumentsthen calculate or otherwise predict by hand what the function should return for these argumentsand write the comparison in the test function test function can include multiple tests we can have multiple assert statements in single test function this can be useful if we want to test function with different arguments for instanceif we write test function for one of the piecewise-defined mathematical functions considered earlier in this it would be natural to test all the separate intervals on which the function is defined the following code illustrates how this can be donefrom math import sinpi def ( )if < <pi
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 =the tolerance tol is some small numberchosen by the programmerthat is small enough that we would consider difference of this magnitude insignificantbut greater than the machine precision ( in practicecomparing floats using =will quite often workbut sometimes it fails and it is impossible to predict when this will happen the code therefore becomes unreliableand it is much safer to compare with tolerance on the other handwhen we work with integers we can always use =one could argue that the test function code above is quite inelegant and repetitivesince we repeat the same lines multiple times with very minor changes since we only repeat three linesit might not be big deal in this casebut if we included more assert statements it would certainly be both boring and error-prone to write code in this way in the previous we introduced loops as much more elegant tool or performing such repetitive tasks using lists and for loopthe example above can be written as followsfrom math import sinpi def ( )if < <pireturn sin(xelsereturn def test_f()x_vals [- pi/ exp_vals [ tol - for xexp in zip(x_valsexp_vals)assert abs( ( )-exptolf'failed for { }expected {exp}but got { ( )}python tools for automatic testing an advantage of following the naming convention for test functions defined above is that there are tools that can be used to automatically run all the test functions in file or folder and report if any bug has sneaked into the code the use of such automatic testing tools is essential in larger development projects with multiple people
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 in terminal terminalpytest terminalpytest my_python_project py if we pass it file namepytest will look for functions in this file with name starting with test_as specified by the naming convention above all these functions will be identified as test functions and called by pytestregardless of whether the test functions are actually called from elsewhere in the code after executionpytest will print short summary of how many tests it foundand how many that passed and failed for larger software projectsit might be more relevant to give directory name as argument to pytestas in the first line above in this casethe tool will search the given directory (here the directory we are currently inand all its sub-directories for python files with names starting or ending with test ( test_math pymath_test pyetc all these files will be searched for test functions following the naming conventionand these will be run as above large software projects typically have thousands of test functionsand it is very convenient to collect them in separate file and use automatic tools such as pytest for the smaller programs we write in this courseit can be just as easy to write the test functions in the same file as the functions being tested it is important to remember that test functions run silently if the test passesthat iswe only obtain an output if there is an assertion errorotherwise nothing is printed to the screen when using pytest we are always given summary specifying how many tests were runbut if we include calls to the test functions directly in the py fileand run this file as normalthere will be no output if the test passes this can be confusingand one is sometimes left wondering if the test was called at all when first writing test functionit can be useful to include print-statement inside the functionsimply to verify that the function is actually called this statement should be removed once we know the function works correctly and as we become used to how the test functions work 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,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 input from usersmost often through graphical user interface (guihoweveralthough guis dominate in modern human-computer interactionother ways of interacting with computer programs can be just as efficient andin some casesfar more suitable for processing large amounts of data and automating repetitive tasks in this we will show how we can extend our programs with simple yet powerful systems for user input in particularwe will see how program can receive command line arguments when it is runhow to make program stop and ask for user inputand how program can read data from files side effect of allowing users to interact with programs is that things will often go wrong users will often provide the wrong inputand programs should be able to handle such events without simply stopping and writing cryptic error message to the screen we will introduce concept known as exception handlingwhich is widespread system for handling errors in programsused in python and many other programming languages finallyin this we shall see how to create our own modules that can be imported for use in other programsjust as we have done with the math module in previous reading user input data so farwe have implemented various mathematical formulas that involved input variables and parametersbut all of these values have been hard-coded into the programs to introduce new exampleconsider the following formulawhich gives an estimate of the atmospheric pressure as function of (cthe author( sundnesintroduction to scientific programming with pythonsimula springerbriefs on computing
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 for different altitudeswhichin this codewould require editing the line to change the respective variableand then rerunning the program this solution could be acceptable for programs we write and use ourselvesbut it is not how we are used to interacting with computers in particularif we write programs that could be used by othersediting the code this way is inconvenient and can easily introduce errors for our programs to be robust and usablethey need to be able to read relevant input data from the user we will consider three different ways to accomplish thiseach with its strengths and weaknesses we will (icreate programs that stop and ask for user inputand then continue the execution when the input is received(iienable our programs to receive command line argumentsthat isarguments provided when we run the program from the terminaland (iiimake the programs read input data from files obtaining input from questions and answers natural extension of this program is to allow it to ask the user for value of hand then compute and output the corresponding atmospheric pressure python function called input provides exactly this functionality for instance line such as input('input the altitude (in meters):'will make the program stop and display the text input the altitude (in meters)in the terminaland then continue when the user presses enter the complete code could look like from math import exp input('input the altitude (in meters):' float(hp #sea level pressure (kpa#scale height (mp exp(- / print(
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 can use it in computations forgetting this line in the code above will lead to an error in the line that calculates amountsince we would by trying to multiply string with float from these considerationswe can also imagine how easy it is to break the program above the user can type any stringor simply press enter (which makes an empty string)but the conversion float(honly works if the string is number as another exampleconsider program that asks the user for an integer and prints the first even numbersn int(input(' =')for in range( + )print( *ihere we convert the input text using int)since the range function only accepts integer arguments just as in the example abovethe code is not very robustsince it will break from any input that cannot be converted to an integer later in this we will look at ways to handle such errors and make the programs more robust command line arguments are words written after the program name when working in unix-style terminal window ( maclinuxwindows powershell)we often provide arguments when we run command these arguments can be names of files or directoriesfor examplewhen copying file with cpor they can change the output from the commandsuch as ls - to obtain more detailed output from the ls command anyone who is used to working in unix-style terminals will be familiar with commands like theseterminal terminalcp - yourdir /mydir terminalls - terminalcd /mydir some commands require arguments for instanceyou receive an error message if you do not give two arguments to cp while other arguments are optional standard unix programs make heavy use of command line arguments(tryfor instancetyping man ls)because they are very efficient
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 calculation program abovebut now we want the altitude to be specified as command line argument rather than obtained by stopping and asking for input for instancewe want to run the program as followssterminal terminalpython altitude_cml py to use command line arguments in python programwe need to import module named sys more specificallythe command line argumentsorin realityany words we type after the command python altitude pyare automatically stored in list named sys argv (short for argument valuesand can be accessed from thereimport sys from math import exp sys argv[ float(hp #sea level pressure (kpa#scale height (mp exp(- / print(pherewe see that we pull out the element with index one from the sys argv listand convert it to float just as the input provided with the input function abovethe command line arguments are always strings and need to be converted to floats or integers before they are used in computations the sys argv variable is simply list that is created automatically when your python program is run the first elementsys argv[ is the name of the py-file containing the program the remainder of the list is made up of whatever words we type after the program filename words separated by space become separate elements in the list nice way to gain feel for the use of sys argv is to test simple program that will just print out the contents of the listfor instanceby writing this simple code into the file print_cml pyimport sys print(sys argv
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 read in string containing blanks as single command line argumentwe need to use quotation marks to override the default behavior of each word being treated as separate list element flexible user input with eval and exec generallythe safest way to handle input data in the form of text strings is to convert it to the specific variable type needed in the program we did this aboveusing the type conversions intand float)and we will see below how such conversions can be made failproof and handle imporper user input howeverpython also offers couple of more flexible functions to handle input datanamelyeval and execwhich are nice to know about extensive use of these functions is not recommendedespecially not in larger programssince the code can become messy and error-prone howeverthey offer some flexible and fun opportunities for handling input data starting with evalthis function simply takes string as input and evaluates it as regular python expressionjust as if it were written directly into the program of courses must be legal python expressionotherwise the code stops with an error message the following interactive python session illustrates how eval workss ' + eval(sr type(rr eval('[ [ ]' [ type(
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('operand ') print( '{type( ){type( )becomes {type( )with value{ }'this code can handle multiple input types if we save the code in file add_input py and run it from the terminalwe canfor instanceadd integer and float numbersas interminal terminalpython add_input py operand operand becomes with value or two listsas followsterminal terminalpython add_input py operand [ , operand [- , , becomes with value [ - we could achieve similar flexibility with conventional type conversionthat isusing float( )int( )and so onbut that would require much more programming to correctly process the input strings the eval function makes such flexible input handling extremely compact and efficientbut it also quickly breaks if the input is slightly wrong consider the following examplesterminal terminalpython add_input py operand ( , operand [ , traceback (most recent call last)file "add_input py"line in typeerrorcan only concatenate tuple (not "list"to tuple terminalpython add_input py
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 examplewe try to make the program add two stringswhich usually works finefor instance "one+"onebecomes the string "oneonehoweverthe eval function breaks when we try to input the first string to understand whywe need to think about what the corresponding line really means we try to make the assignment eval('one')which is equivalent to writing onebut this line does not work unless we have already defined variable named one remedy to this problem is to input the strings with quotation marksas in the following example terminal terminalpython add_input py operand "oneoperand "twobecomes with value onetwo these examples illustrate the benefits of the eval functionand also how it easily breaks programs and is generally not recommended for "real programsit is useful for quick prototypesbut should usually be avoided in programs that we expect others to use or that we expect to use ourselves over longer time frame the other "magictext handling function is named execand it is fairly similar to eval howeverwhereas eval evaluates an expressionexec executes string argument as one or more complete statements for instanceif we define string " + "eval(sis illegalsince the value of (" + "is statement (an assignment)and not python expression howeverexec(swill work fine and is the same as including the line + directly in the code the following code illustrates the differenceexpression ' + statement ' + eval(expressionexec(statementprint( , #store expression in string store statement in string results are the same
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 the code directly in our program after the call to exec we have defined the function (tand can call this function in the usual way although this example does not seem very usefulthe flexibility of exec becomes more apparent if we combine it with actual user input for instanceconsider the following codewhich asks the user to type mathematical expression involving and then embeds this expression in python functionformula input('write formula involving 'code ""def ( )return {formula""from math import make sure we have sincoslogetc exec(codeturn string formula into live function #now the function is definedand we can ask the #user for values and evaluate (xx while is not nonex eval(input('give (none to quit)')if is not noney (xprint( ' ({ })={ }'while the program is runningthe user is first asked to type formulawhich becomes function then the user is asked to input values until the answer is noneand the program evaluates the function (xfor each the program works even if the programmer knows nothing about the user' choice of (xwhen the program is writtenwhich demonstrates the flexibility offered by the exec and eval functions to consider another examplesaywe want to create program diff py that evaluates the numerical derivative of mathematical expression (xfor given value of the mathematical expression and the value will be given as command line arguments the program could be used as followsterminal terminalpython diff py 'exp( )*sin( ) numerical derivative-
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( - ))/( *hprint( 'numerical derivative{numerical_derivative(fx)}'again we see that the flexibility of the exec function enables us to implement fairly advanced functionality in very compact program reading data from files scientific data are often available in filesand reading and processing data from files have always been important tasks in programming the data science revolution that we have witnessed in recent years has only increased their importance furthersince all data analysis starts with being able to read data from files and store them in suitable data structures to start with simple exampleconsider file named data txt containing single column of numbers we assume that we know in advance that there is one number per linebut we do not know the number of lines how can we read these numbers into python program
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 readingas specified with the letter rand creates file object named infile if we want to open file for writingwhich we will consider laterwe have to use open('data txt',' 'the default is rsoto read file we could also simply write infile open('data txt'howeverincluding the can be good habitsince it makes the purpose of the line more obvious to anyone reading the code in the second linewe enter regular for loopwhich will treat the object infile as list-like object and step through the file line by line for each pass through the for loopa single line of the file is read and stored in the string variable lineand inside the for loop we add any code we want for processing this line when there are no more lines in the filethe for loop endsjust as when looping over regular list the final lineinfile close()closes the file and makes it unavailable for further reading this line is not very important when reading from filesbut it is good habit to always include itsince it can make difference when writing to files to return to the concrete data file abovesay the only processing we want is to compute the mean value of the numbers in the file the complete code could look like thisinfile open('data txt'' 'open file mean lines for line in infilenumber float(lineline is string mean mean number lines + mean mean/lines print( 'the mean value is {mean}'this is standard way to read files in pythonbutas usualin programming there are multiple ways to do things an alternative way of opening filewhich many will consider more modernis by using the following codewith open('data txt'' 'as infilefor line in infiledo something with line open file the first lineusing with and as probably does not look familiarbut it does essentially the same thing as the line infile openin the first example one important difference is thatif we use with we see that all file reading and processing must be put inside an indented block of codeand the file is automatically closed when this block has been completed therefore
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 been openedthere are couple of alternatives to the approach above for instancewe can read all the lines into list of strings (linesand then process the list items one by onelines infile readlines(infile close(for line in linesprocess line this approach is very similar to the one used abovebut here we are done working directly with the file after the first lineand the for loop instead traverses the list of strings in practice there is not much difference usuallyprocessing files line by line is very convenientand our good friend the for loop makes such processing quite easy howeverfor files with no natural line structureit can sometimes be easier to read the entire text file into single stringtext infile read(process the string text the data txt file above contain single number for each linewhich is usually not the case more ofteneach line contains many data itemstypically both text and numbersand we might want to treat each one differently for this purpose python' string type has built-in method named split that is extremely useful say we define string variable with some words separated by blank spaces thencalling split(will simply return list containing the individual words in the string by defaultthe words are assumed to be separated by blanksbut if we want different separatorwe can pass it as an argument to split the following code gives some exampless "this is typical stringcsvline "excel;sheets;often;use;semicolon;as;separatorprint( split()print(csvline split()print(csvline split(';')['this''is'' ''typical''string'['excel;sheets;often;use;semicolon;as;separator'['excel''sheets''often''use''semicolon''as''separator'we see that the first attempt to split the string csvline does not work very wellsince the string contains no spaces and the result is therefore list of length one specifying the correct separatoras in the last linesolves the problem to illustrate the use of split in the context of file dataassume we have file with data on rainfall