Example: bankruptcy

A Python 2.7 programming tutorial

A W. Shipman2013-07-0712:18 AbstractA tutorialfor the Pythonprogramminglanguage, availablein Webform1and alsoas a PDFdocument2. of Contents1. StartingPythonin 22. Python ' The 83. The 184. Functionsand operatorsfor Indexingthe positionsin a List Therange() Onevaluecan 275. Operationson A namespaceis like a 336. Conditionsand A 401 407. Howto writea : : Returningvaluesfroma Functionargumentlist 479. A moduleis a 5110. Inputand positioningfor 5411. Introductionto briefhistoryof :A list of : A cycleof an 661.

A Python 2.7 programming tutorial Version 2.0 John W. Shipman 2013-07-07 12:18 Abstract A tutorial for the Python programming language, release 2.7.

Tags:

  Programming, Python, Tutorials, A python 2, 7 programming tutorial

Information

Domain:

Source:

Link to this page:

Please notify us if you found a problem with this document:

Other abuse

Transcription of A Python 2.7 programming tutorial

1 A W. Shipman2013-07-0712:18 AbstractA tutorialfor the Pythonprogramminglanguage, availablein Webform1and alsoas a PDFdocument2. of Contents1. StartingPythonin 22. Python ' The 83. The 184. Functionsand operatorsfor Indexingthe positionsin a List Therange() Onevaluecan 275. Operationson A namespaceis like a 336. Conditionsand A 401 407. Howto writea : : Returningvaluesfroma Functionargumentlist 479. A moduleis a 5110. Inputand positioningfor 5411. Introductionto briefhistoryof :A list of : A cycleof an 661.

2 IntroductionThisdocumentcontainssometuto rialsfor the Pythonprogramminglanguage,as of Thesetutorialsaccompanythe freePythonclassestaughtby the at the Starting Pythonin conversationalmodeThistutorialmakesheavy use of Python ' this way,you will see an initialgreetingmessage,followedby the prompt >>> . On a TCCworkstationin Windows,fromtheStartmenu,selectAll Programs Python IDLE( Python GUI). Youwill see somethinglike this:3 programmingtutorial2 For Linuxor MacOS,froma shellprompt(suchas $ for thebashshell),type:pythonYouwill see somethinglike this:$ (r271:86832,Apr 12 2011,16:15:16)[ (RedHat )]on linux2 Type"help","copyright","credits"or "license"for moreinformation.>>>Whenyousee the >>> prompt,youcan typea Pythonexpression,andPythonwillshowyouthe resultof that a deskcalculator.

3 (That'swhywe sometimesreferto conversationalmodeas calculatormode .)For example:>>> 1+12>>>Eachsectionof this tutorialintroducesa groupof Python 'snumerictypesPrettymuchall programsneedto do severalwaysof representingnumbers,and an assortmentof operatorsto operateon BasicnumericoperationsTo do numericcalculationsin Python ,you can writeexpressionsthatlookmoreor less like algebraicexpressionsin + operatoris addition; - is subtraction;use * to multiply;and use / to someexamples:>>> 99 + 1100>>> 1 - 99-98>>> 7 * 535>>> 81 / 993A programmingtutorialNewMexicoTechComputer CenterThe examplesin this documentwill oftenuse a lot of extraspacebetweenthe partsof the expression,just to makethingseasierto ,thesespacesare not required:>>> 99+1100>>> 1-99-98 Whenan expressioncontainsmorethanone operation,Pythondefinesthe usualorderof operations,so thathigher-precedenceoperationslike multiplicationanddivisionare this example,eventhoughthe multiplicationcomesafterthe addition,it is donefirst.

4 >>> 2 + 3 * 414If you wantto overridethe usualprecedenceof Pythonoperators,use parentheses:>>> (2+3)*420 Here'sa resultyou maynot expect:>>> 1 / 50 You mightexpecta resultof , not ,Pythonhas differentkindsof decimalpointis consideredaninteger, a any of the numbersinvolvedcontaina decimalpoint,the computationis doneusingfloatingpointtype:>>> / >>> / the last digita one?In Python (andin prettymuchall othercontemporaryprogramminglanguages),m anyreal numberscannotbe representationof a slighterrorin the ,but in conversationalmode,Pythondoesn'tknowhowm uchprecisionyou want,soyou get a ridiculousamountof precision,and this showsup the fact that somevaluesare use Python 'sprintstatementto displayvalueswithoutquiteso muchprecision:>>> 's okayto mix integerandfloatingpointnumbersin the coercedto theirfloatingpointequivalents.

5 >>> >>> print1 willlearnaboutPython'sstringformatmethod , whichallowsyouto specifyexactlyhowmuchprecisionto use now,let's moveon to somemoreof the operatorson programmingtutorial4 The % operatorbetweentwo numbersgivesyou themodulo. Thatis, the expression x%y returnsthe remainderwhenxis dividedbyy.>>> 13 % 53>>> >>> expressedas x**y , meaningxto theypower.>>> 2 ** 8256>>> 2 ** 301073741824>>> ** >>> ** >>> ** +30 Thatlast number, +30, is an readas to the 30thpower .Similarly,a readas to the minus24thpower .So far we haveseenexamplesof the integertype,whichis calledintin Python ,and thefloating-pointtype,calledthefloattype in ,147,483,648and 2,147,483,647(inclusive).

6 Thereis anothertypecalledlong, that can this typewheneveran expressionhas valuesoutsidethe seeletter L appearat the end of suchvalues,but theyact just like regularintegers.>>> 2 ** 501125899906842624L>>> 2 ** 1001267650600228229401496703205376L>>> 2 ** The assignmentstatementSo far we haveworkedonlywithnumericconstantsand attacha nameto a value,and that valuewill stayaroundfor the rest of letteror the underbar(_) character;the rest of the namemayconsistof letters,underbars,or case-sensitive:the nameCountis a programmingtutorialNewMexicoTechComputer CenterFor example,supposeyou wantedto answerthe question, howmanydaysis a millionseconds? Wecan startby attachingthe namesecto a valueof a million:>>> sec = 1e6>>> statementof this typeis calledanassignmentstatement.

7 To computethe numberof minutesin a millionseconds,we divideby 60. To convertminutesto hours,we divideby 60 converthoursto days,divideby 24, and that is thefinalanswer.>>> minutes= sec / >>> >>> hours=minutes/60>>> >>> days=hours/24.>>> >>> printdays,hours,minutes, attachmorethanone nameto a a seriesof names,separatedby equalsigns,likethis.>>> total= remaining= 50>>> printtotal,remaining50 50 The generalformof an assignmentstatementlookslike this:name1=name2= .. =expressionHereare the rulesfor evaluatingan assignmentstatement: Eachnameiis letteror the un-derbar(_) character,andthe remainingcharactersmustbe letters,digits,or :skateKey;_x47;sum_of_all_fears. Theexpressionis any Pythonexpression.

8 Whenthe statementis evaluated,firsttheexpressionis evaluatedso thatit is a ,if theexpressionis (2+3)*4 , the resultingsinglevalueis the the namesnameiareboundto that meanfor a nameto be boundto a value?Whenyou are usingPythonin conversationalmode,the namesand valueyou defineare storedin an areacalledtheglobalnamespace. Thisareais likea two-columntable,withnameson the left and valueson the an startwitha brandnewPythonsession,and typethis line:>>> i = 5100 Hereis whatthe globalnamespacelookslike afterthe executionof this programmingtutorial6 Global namespaceNameValueinti5100In this diagram,the valueappearingon the rightshowsits type,int(integer),and the value, Python ,valueshavetypes,but namesarenotassociatedwithany namecan be boundto avalueof any typeat any , a Pythonnameis like a luggagetag: it identifiesa value,and lets youretrieveit anotherassignmentstatement,and a diagramshowinghowthe globalnamespaceappearsafterthe statementis executed.

9 >>> j = foo = i + 1 Name Valueint5101int5100ifoojThe expression i + 1 is equivalentto 5100+ 1 , sincevariableiis boundto the the integervalue5101,and thenthe namesjandfooare bothboundto this situationas beinglike one pieceof baggagewithtwo tagstied to 'sexaminethe globalnamespaceafterthe executionof this assignmentstatement:>>> foo = foo + 1 Name Valueint5101int5100i5102intfoojBecausefo ostartsout boundto the integervalue5101,the expression foo+ 1 simplifiesto ,foo = foo + 1doesn'tmakesensein algebra!However,it is a commonwayfor programmersto add one to a namejis still boundto its old value, More mathematical operationsPythonhas a numberof call a functionin Python ,use this generalform:f(arg1,arg2.)

10 Thatis, use the functionname,followedby an openparenthesis ( , followedby zeroor moreargumentsseparatedby commas,followedby a closingparenthesis ) .For example,theroundfunctiontakesone numericargument,and returnsthe nearestwholenumber(as afloatnumber).Examples:>>> round( ) >>> round( ) >>> round( ) resultof that last caseis somewhatarbitrary, is and However,asin mostothermodernprogramminglanguages,the valuechosenis the one :>>> round( ) >>> round( ) >>> round( ) historicalreasons,trigonometricandtransc endentalfunctionsare not built-into youwantto do calculationsof thosekinds,youwillneedto tell Pythonthatyouwantto use line:>>> frommathimport*Onceyouhavedonethis,youwi llbe ableto use a numberof example,sqrt(x)computesthe squarerootofx:>>> sqrt( ) >>> sqrt(81) >>> sqrt(100000) addstwo predefinedvariables,pi(as in ) ande, the baseof naturallogarithms.


Related search queries