Handbook of the Physics Computing Course Michael Williams December3, 2002 Copyright(cid:0)c 2002MichaelWilliams;thisdocumentmaybecopied,distributedand/ormodifiedundercertaincondi- tions,butitcomesWITHOUTANYWARRANTY;seetheDesignScienceLicenseformoredetails. Acopyofthelicenseis: (cid:1) includedintheLATEXdistributionofthisdocument—seehttp://users.ox.ac.uk/sann1276/python. (cid:1) alwaysavailableathttp://dsl.org/copyleft/dsl.txt. ii CONTENTS 1 Introduction 1 1.1 ThePythontrial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.2 Typographicalconventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 2 Usingthesystem 3 2.1 Loggingin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 2.2 IDLEbasics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 2.3 ProgrammingusingIDLE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 2.4 Casesensitivity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 3 TheelementsofPython 7 3.1 Helloworld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 3.2 Interpreters,modules,andamoreinterestingprogram . . . . . . . . . . . . . . . . . . . . . . . . . 7 3.3 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 3.4 Inputandoutput . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 3.5 Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 3.6 forloops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 3.7 ifstatements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 3.8 whileloops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 3.9 Usinglibraryfunctions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 3.10 Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 3.11 Makingyourownfunctions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 3.12 Fileinputandoutput . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 3.13 Puttingitalltogether . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 4 GraphicaloutputandadditionalPython 27 4.1 Graphicaloutput . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 4.2 ArraysinPython . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 4.3 Functionsyoumayneedforthefirst-yearproblems . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 4.4 Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 4.5 Pythondifferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 4.6 Takingyourinterestfurther . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 A Errors 35 A.1 AttributeErrors,KeyErrors,IndexErrors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 A.2 NameErrors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 A.3 SyntaxErrors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 A.4 TypeErrors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 B ReservedWords 37 iii iv CHAPTER ONE Introduction 1.1 The Python trial Thankyouforparticipatinginthistrialofaproposednewfirstyearcomputingcourse. Duringthistrialwewouldlike youtoconsultdemonstratorsasmuchasyoulike. Itisbeingrunforustoironouttheproblemsinthecourse,andso wewillbemostappreciativeofanyfeedbackthatyoucangiveusaboutthecourseorthehandbook. Ofcourse,we alsohopeyouwillfindthetrialinterestinganduseful! LikethePascalcourseyoudidlastyearthistrialconsistsofthefollowingelements: Usingthesystem Logging in; using the graphical interface; files; using the Python interpreter; creating, editing, storingandrunningprograms. YouwilllearnsomeoftheskillsassociatedwiththeuseoftheUNIXoperating system. TheelementsofPython Learning enough of a programming language to write simple but useful programs, while beingintroducedtotheconceptsofproceduralprogramming. TointroduceyourselftothebasicsofPythonyouwillneedtoreadthroughChapter3,“TheelementsofPython” anddotheexercisesgivenasyougoalong. Ifyoudonotunderstandhowtotackleaparticularexerciseplease consultademonstrator. Thehandbookshouldcontainalltheinformationyouneedtocompletetheexercisesandtheproblemyouwill bedoing. ProgrammingProblems Once you have gone through the introduction to Python we would like you to attempt a more substantialproblem. Youmay selectonefrom the followinglist (youmay selectthe oneyou did in the firstyearifyouwish): CO11 QuadraticEquation;straightlinefittingbyleastsquares CO12 NucleardecayandtheDopplereffect CO13 NumericalIntegrationbySimpson’sruleandbyaMonteCarlomethod CO14 Solutionofnon-linearequations;solutionofadifferentialequation CO15 Polynomialcurvefittingbyleastsquares CO16 Graphplotting;FourierAnalysis Note: whicheverproblemyouchoose,forthepurposesofthetrialitwillberecordedasexperimentCO91 Whilst it is not required, we would like you to use your logbooks to make notes as you do the course; in anycase, you will not need to produce a write-up of the problem you attempt. Rather, we will ask you to discuss it with a demonstratorandfillinaquestionnaire. This course deliberately covers only a subset of Python, which is an extremely powerful and flexible language. In doing the course you should acquire skills applicable both to Python and to programming in general. Python has 1 beenchosenbecauseitispossibletoteachenoughofthelanguagetowriteusefulprogramsrelativelyquickly,yetit is potentially a very powerful language, which is being increasingly used throughout academia and the commercial softwareindustry. 1.2 Typographical conventions Thishandbookusesthefollowingtypographicalconventions: MostofthedocumentappearsintheTimesfont. Typewriter fontisusedforanythingtyped,e.g. PythoncodeorUNIXcommands. Sansserifisusedformenuandapplicationnames Newtermsandotherpiecesofjargonarewritteninitalicsthefirsttimetheyareused. [Thesewillbedescribedina glossaryinalateredition]. 2 Chapter1. Introduction CHAPTER TWO Using the system 2.1 Logging in SitatoneoftheSunterminals. Movethemouse: thescreenshouldcomeon;ifitdoesn’tafterafewseconds,press thepowerbuttoninthebottom-rightcornerofthemonitor,sothegreenLEDislit. You should see a login panel: using lower case, enter your usual Physics username where indicated and then press Returnbutbeforeyouenteryourpassword, ensurethatthegraphicontherightsays“SolarisCommonDesktop Environment”. If itdoes not, thenclick andhold the Optionsbutton, andselectCommon Desktop Environment fromtheSessionmenu. NowenteryourpasswordandpressReturn. Theloginpanelshoulddisappearandafterafewseconds, youshouldseevariouswindowsappearonthescreen. If youwanttobeabletousetheNetscapewebbrowser—whichwerecommend—clickAcceptinitsLicensepanel(a Netscapebrowserwindowwillthenappear,whichyoucanminimisebyclickingonthe“dot”buttonatthetop-right ofitswindow). Youshouldalso mimimisetheHelp Viewer andFile Managerwindowsinthesame manner. You shouldnowbeleftwithasingleTerminalwindow. IfyoudonotseeaTerminalwindow,thenyoucangetanewoneatanytimebyclickingonceontheterminaliconat thebottom-rightofthescreen(itshouldbethethirdiconfromtheright). ClickintheTerminalwindowsoitsborder turnsdarkpink(thisindicatesthatyoucantypethingsintoit).TerminalsprovideaccesstowhatisknownastheUNIX command-line,orshell. AUnixshellisabitliketheDOS-promptinMicrosoftWindows,butitisfarmorepowerful andflexible: itmakesavailablehundredsofcommands,utilitiesandprograms. Theshellindicatesthatitisreadyto receivecommandsbydisplayingthefollowing1prompt: rayleigh% SomebasichelpandinformationaboutUnixcommandsisavailablebytypinghelpinaTerminalwindow. Mostly, however,youwillnotneedtousetheshellbecausewehavemadeavailableasingle,integratedapplicationfordoing PythonprogrammingcalledIDLE. 2.2 IDLE basics ThissectiondescribestheIDLEapplicationthatyouwillbeusingwhenyoustartwritingyourownPythonprograms inthenextchapter.YouwillprobablyneedtoreferbacktoitwhenyoustartworkingthroughChapter3. IDLEisPython’sIntegratedDeveLopmentEnvironment;inotherwordsitisanapplicationwhichenablesyoutoboth writeandrunPythonprograms. 2 TostartupIDLEtypeidleattheshellpromptandpresstheReturnkey: 1Thisisthedefaultshellprompt:itcanbecustomized. 2IfyouarefamiliarwithUNIXorLinuxyoumayalternativelyuseyourfavouriteUNIXtext-editortowriteyourPythonprograms,andthenrun themyourselfusingthepythoncommand.However,IDLEdoesprovideaniceenvironmentfordevelopingPythoncode,sowerecommendyou tryusingit. 3 rayleigh% idle Note: idleistypedentirelyinlowercase—seeSection2.4,“Casesensitivity”. Atthispoint,youmaywishtominimisetheTerminalwindow;doNOTcloseitorIDLEwillbekilled! AfterafewsecondsanewwindowcalledPythonShellwillappear.ThisisIDLE’sinterfacetothePythoninterpreter. Aninterpreterisaprogramwhichtranslatestheprogramsourcecodeyouenterintomachinecodewhichthecomputer canunderstandandrun. Chapter3explainsallaboutusingthePythoninterpreter. IDLE also includes an editor which is an application, rather like a simple word-processor, that you use to write programs(or indeed anykind oftext). IDLE’s editor has been customizedto makeit particularlyusefulfor writing Python programs, and it should be fairly intuitive to use. Documents are opened, closed and saved by selecting commandsintheFilemenu. 2.2.1 Creating a new program SelectingNewWindowfromtheFilemenuwillopenanemptyeditorwindowcalledUntitled. 2.2.2 Opening existing programs YoucanretrieveapreviouslysavedprogrambychoosingOpenfromtheFilemenuandselectingthefiletoopen. 2.2.3 Saving programs After typing or editing a Python program, save the file by selecting Save from the File menu. The first time you saveafile,SavewillactuallybehavelikeSaveAs;inotherwords,asmallwindowwillappearwhereyoucanenter thenameyouwishtogiveyourprogram. Onsubsequentoccasions,Savewillsimplysavethefile. Oncesaved,the programremainson-screenforfurthereditingifyouwish. 2.2.4 Closing programs IfyoureallyhavefinishededitingyourprogramthenchooseClosefromtheFilemenu. Ifthereareunsavedchanges youwillbepromptedtosavethem. In general, when you have finished with a window you should close it rather than minimising it as otherwise your screenwillbecomeclutteredwithlotsofminimisedwindowicons. 2.3 Programming using IDLE As you will see in Section 3.2 it is possible to write programs either interactively or by using the editor. You will probablyneedtoreferbacktothissectionwhenyoustartwritingyourownprograms. 2.3.1 Using the interactive interpreter ManyoftheexamplesinthishandbookusePython’sinteractiveinterpreter. Ifyoudon’talreadyhaveoneopen,you cangetaninteractivewindow(aPythonShell)byselectingPythonShellfromtheRunmenu. 4 Chapter2. Usingthesystem