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. 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 >>>.
2 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.(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.
3 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.>>> 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?
4 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.>>> >>> 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.
5 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).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.
6 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. 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?
7 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.>>> 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!
8 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, .. )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:>>> printpi, 'san exampleof a functionthat functionatan2(dy,dx) returnsthe arctangentof a line whoseslopeisdy/dx.
9 >>> atan2( , ) programmingtutorial8>>> atan2( , ) >>> atan2( , ) >>> a completelist of all the facilitiesin themathmodule,see thePythonquickreference4. Hereare somemoreexamples;logis the naturallogarithm,andlog10is the commonlogarithm:>>> log(e) >>> log10(e) >>> exp ( ) >>> sin ( pi / 2 ) >>> cos(pi/2) ,cos( /2)shouldbe ,like prettymuchall othermodernprogramminglanguages,transcen dentalfunctionslike this use 10-17is, afterall, you mayfindusefulin certainsituations: floor(x)returnsthe largestwholenumberthat is less thanor equaltox. ceil(x)returnsthe smallestwholenumberthat is greaterthanor equaltox.>>> floor( ) >>> floor( ) >>> floor( ) >>> floor( ) >>> ceil( ) >>> ceil( ) >>> ceil( ) >>> ceil( ) thefloorfunctionalwaysmovestoward- (minusinfinity),andceilalwaysmovestoward + .4 programmingtutorialNewMexicoTechComputer Center3. Character stringbasicsPythonhas extensivefeaturesfor handlingstringsof two types: Astrvalueis a stringof zeroor commoncharactersyousee on NorthAmericankeyboardsall use this characterset is ASCII5, forAmericanStandardCodefor has one surprisingproperty:all capitallettersare consideredless thanall lowercaseletters,so the string"Z"sortsbeforestring"a".
10 Aunicodevalueis a stringof zeroor Unicodecharactersetcoversjust abouteverywrittenlanguageand 'llmainlytalkaboutworkingwithstrvalues,b ut mostunicodeoperationsare similaroridentical,exceptthatUnicodelite ralsare precededwiththe letteru: for example,"abc"is typestr,butu"abc"is StringliteralsIn Python ,youcan enclosestringconstantsin eithersingle-quote('..') or double-quote("..")characters.>>> cloneName= 'Clem'>>> cloneName'Clem'>>> printcloneNameClem>>> fairName= "FutureFair">>> printfairNameFutureFair>>> fairName'FutureFair'Whenyou displaya stringvaluein conversationalmode,Pythonwill usuallyuse ,the valuesare the sameregardlessof whichkindof quotesyou use. Notealso that theprintstatementshowsonlythe contentof a string,withoutany convertan integer(inttype)valueito its stringequivalent,use the function str(i) :>>> str(-497)'-497'>>> str(000)'0'The inverseoperation,convertinga stringsbackinto an integer,is writtenas int(s) :>>>>>> int("-497")-497>>> int("-0")0>>> int ( "012thisain'tno number")Traceback(mostrecentcalllast):5 programmingtutorial10 File"<stdin>",line1, in ?