You are on page 1of 12

11/07/12

3. An Informal Introduction to Python Python v2.7.3 documentation

3.AnInformalIntroductiontoPython
Inthefollowingexamples,inputandoutputaredistinguishedbythepresenceorabsenceof prompts( > > > and . . to repeat the example, you must type everything after the prompt, . ): when the prompt appears lines that do not begin with a prompt are output from the interpreter.Notethatasecondarypromptonalinebyitselfinanexamplemeansyoumust typeablanklinethisisusedtoendamultilinecommand. Manyoftheexamplesinthismanual,eventhoseenteredattheinteractiveprompt,include comments.CommentsinPythonstartwiththehashcharacter, # ,andextendtotheendof thephysicalline.A comment may appear at the start of a line or following whitespace or code, but not within a string literal. A hash character within a string literal is just a hash character.SincecommentsaretoclarifycodeandarenotinterpretedbyPython,theymay beomittedwhentypinginexamples. Someexamples:
#tistefrtcmet hsihisomn SAnhsiheodcmet PM=1#adtistescnomn .nohr! #..adnwatid SRN#Tisntacmet" TIG="hsioomn.

3.1.UsingPythonasaCalculator
Lets try some simple Python commands. Start the interpreter and wait for the primary prompt, > > > .(Itshouldnttakelong.)

3.1.1.Numbers
Theinterpreteractsasasimplecalculator:youcantypeanexpressionatitanditwillwrite thevalue.Expressionsyntaxisstraightforward:theoperators + * , , and / workjustlikein mostotherlanguages(forexample,PascalorC)parenthesescanbeusedforgrouping. Forexample:
>>22 >+ 4 >>#Tisacmet >hsiomn ..22 .+ 4 >>22nomnntesmieaoe >+#adacmetohaelnscd 4 >>(056/ >5*)4 5 >>#Itgrdvsoeunhlo: >neeiiinrtrstefor ..73 ./ 2 >>7 >/3 3 >> >

docs.python.org/tutorial/introduction.html#using-python-as-a-calculator

1/12

11/07/12

3. An Informal Introduction to Python Python v2.7.3 documentation

The equal sign ( ' ' is used to assign a value to a variable. Afterwards, no result is = ) displayedbeforethenextinteractiveprompt:
>>wdh=2 >it0 >>hih* >egt=59 >>wdh*hih >itegt 90 0 >> >

Avaluecanbeassignedtoseveralvariablessimultaneously:
>>x=y=z=0eoxn >#Zr,yadz >>x > 0 >>y > 0 >>z > 0 >> >

Variables must be defined (assigned a value) before they can be used, or an error will occur:
>>#tytcesaneieaibe >roacsnudfndvral ..n . Taeak(otrcnalls) rcbcmseetclat: Fl<ti>,ln,imdl> ie"sdn"ie1n<oue NmErrae''ioeie aero:nmnsntdfnd >> >

There is full support for floating point operators with mixed type operands convert the integeroperandtofloatingpoint:
>>3*37. >.5/15 75 . >>70/2 >. 35 . >> >

Complexnumbersarealsosupportedimaginarynumbersarewrittenwithasuffixof j J or . Complex numbers with a nonzero real component are written as ( e l i a j , or can be ra+mg) createdwiththe c m l x r a , i a ) o p e ( e l m g function.
>>1J >j*1 (10) +j >>1ope(,) >j*cmlx01 (10) +j >>31* >+j3 (+j 33) >>(+j* >31)3 (+j 93) >>(+j/11) >12)(+j (.+.j 1505) >> >

Complex numbers are always represented as two floating point numbers, the real and imaginarypart.Toextractthesepartsfromacomplexnumberz,use z r a and z i a . .el .mg

docs.python.org/tutorial/introduction.html#using-python-as-a-calculator

2/12

11/07/12

3. An Informal Introduction to Python Python v2.7.3 documentation

>>a1505 >=.+.j >>ara >.el 15 . >>aia >.mg 05 .

>> >

Theconversionfunctionstofloatingpointandinteger( f o t ) i t ) l a ( , n ( and l n ( )dontwork og) forcomplexnumbersthereisnoonecorrectwaytoconvertacomplexnumbertoareal number.Use a s z togetitsmagnitude(asafloat)or z r a togetitsrealpart. b() .el
>>a3040 >=.+.j >>fota >la() Taeak(otrcnalls) rcbcmseetclat: Fl<ti>,ln,i ie"sdn"ie1n? TpErra'ovropeofotsb() yero:cntcnetcmlxtlaueasz >>ara >.el 30 . >>aia >.mg 40 . >>asa#sr(.el*.mg*) >b()qtara*2+aia*2 50 . >> >

Ininteractivemode,thelastprintedexpressionisassignedtothevariable _ .Thismeans that when you are using Python as a desk calculator, it is somewhat easier to continue calculations,forexample:
>>tx=1.0 >a25/10 >>pie=105 >rc0.0 >>pie*tx >rca 1.65 252 >>pie+_ >rc 1302 1.65 >>rud_) >on(,2 130 1.6 >> >

Thisvariableshouldbetreatedasreadonlybytheuser.Dontexplicitlyassignavaluetoit youwouldcreateanindependentlocalvariablewiththesamenamemaskingthebuiltin variablewithitsmagicbehavior.

3.1.2.Strings
Besidesnumbers,Pythoncanalsomanipulatestrings,whichcanbeexpressedinseveral ways.Theycanbeenclosedinsinglequotesordoublequotes:
>>'pmeg' >sags 'pmeg' sags >>'os\t >den'' "os'" dent >>"os'" >dent "os'" dent >>'Ys"had' >"e,esi. 'Ys"had' "e,esi. >>""e,"had" >\Ys\esi. 'Ys"had' "e,esi. >> >

docs.python.org/tutorial/introduction.html#using-python-as-a-calculator

3/12

11/07/12

3. An Informal Introduction to Python Python v2.7.3 documentation

>>'In',had' >"s\t"sesi. 'In',had' "s\t"sesi.

Theinterpreterprintstheresultofstringoperationsinthesamewayastheyaretypedfor input:insidequotes,andwithquotesandotherfunnycharactersescapedbybackslashes,to showtheprecisevalue.Thestringisenclosedindoublequotesifthestringcontainsasingle quote and no double quotes, else its enclosed in single quotes. The p i t statement rn producesamorereadableoutputforsuchinputstrings. Stringliteralscanspanmultiplelinesinseveralways.Continuationlinescanbeused,witha backslash as the last character on the line indicating that the next line is a logical continuationoftheline:
hlo="hsiahrlntigcnann\\ elTisarteogsrnotiign svrllnsoetjssyuwuddnC\\ eeaieftxutaooloi.n Nthtwiepcttebgnigohiei\ oetahtsaeaheinnftelns infcn. sgiiat" pithlo rnel

Notethatnewlinesstillneedtobeembeddedinthestringusing \ thenewlinefollowing n thetrailingbackslashisdiscarded.Thisexamplewouldprintthefollowing:


Tisarteogsrnotiig hsiahrlntigcnann svrllnsoetjssyuwuddnC eeaieftxutaooloi. Nthtwiepcttebgnigohieiinfcn. oetahtsaeaheinnftelnssgiiat

Or,stringscanbesurroundedinapairofmatchingtriplequotes: " " ' ' " or ' .Endoflinesdo notneedtobeescapedwhenusingtriplequotes,buttheywillbeincludedinthestring.


pit"" rn" Uaehny[PIN] sg:tigOTOS hipahsuaemsae Dslytisgesg Hhsnmotaetonco otaeHsnmocnett "" "

producesthefollowingoutput:
Uaehny[PIN] sg:tigOTOS hipahsuaemsae Dslytisgesg Hhsnmotaetonco otaeHsnmocnett

Ifwemakethestringliteralarawstring, \ sequencesarenotconvertedtonewlines,but n the backslash at the end of the line, and the newline character in the source, are both includedinthestringasdata.Thus,theexample:
hlo=rTisarteogsrnotiign el"hsiahrlntigcnann\\ svrllnsoetmcsyuwuddnC" eeaieftxuhaooloi. pithlo rnel

docs.python.org/tutorial/introduction.html#using-python-as-a-calculator

4/12

11/07/12

3. An Informal Introduction to Python Python v2.7.3 documentation

wouldprint:
Tisarteogsrnotiign hsiahrlntigcnann\\ svrllnsoetmcsyuwuddnC eeaieftxuhaooloi.

Stringscanbeconcatenated(gluedtogether)withthe + operator,andrepeatedwith * :
>>wrHl'+'' >od='epA >>wr >od 'ep' HlA >>''+wr*> ><od5+'' 'HlAepHlAepHlA' <epHlAepHlAep> >> >

Two string literals next to each other are automatically concatenated the first line above could also have been written w r H l ' ' ' this only works with two literals, not with o d = ' e p A arbitrarystringexpressions:
>>'t''n'#hsik >srig<Tiso 'tig srn' >>'t'srp)+'n'#hsik >sr.ti(ig<Tiso 'tig srn' >>'t'srp)'n'#hsinai >sr.ti(ig<Tisivld Fl<ti>,ln,i ie"sdn"ie1n? 't'srp)'n' sr.ti(ig ^ SnaErrnaiytx ytxro:ivldsna >> >

Stringscanbesubscripted(indexed)likeinC,thefirstcharacterofastringhassubscript (index)0.Thereisnoseparatecharactertypeacharacterissimplyastringofsizeone. LikeinIcon,substringscanbespecifiedwiththeslicenotation:twoindicesseparatedbya colon.


>>wr[] >od4 '' A >>wr[:] >od02 'e H' >>wr[:] >od24 'p l' >> >

Sliceindiceshaveusefuldefaultsanomittedfirstindexdefaultstozero,anomittedsecond indexdefaultstothesizeofthestringbeingsliced.
>>wr[2#Tefrttocaatr >od:]hiswhrces 'e H' >>wr[:#Eeyhnxettefrttocaatr >od2]vrtigecphiswhrces 'p' lA >> >

UnlikeaCstring,Pythonstringscannotbechanged.Assigningtoanindexedpositioninthe stringresultsinanerror:
>>wr[]='' >od0x Taeak(otrcnalls) rcbcmseetclat: Fl<ti>,ln,i ie"sdn"ie1n? >> >

docs.python.org/tutorial/introduction.html#using-python-as-a-calculator

5/12

11/07/12

3. An Informal Introduction to Python Python v2.7.3 documentation

TpErrbetdeouprtmasgmn yero:ojcosntspotiesinet >>wr[1Slt >od:]='pa' Taeak(otrcnalls) rcbcmseetclat: Fl<ti>,ln,i ie"sdn"ie1n? TpErrbetdeouprlcsinet yero:ojcosntspotsieasgmn

However,creatinganewstringwiththecombinedcontentiseasyandefficient:
>>''+wr[: >xod1] 'ep' xlA >>'pa'+wr[] >Sltod4 'paA Slt' >> >

Heresausefulinvariantofsliceoperations: s : ] + s i ] [ i [ : equals s .
>>wr[2od2] >od:]+wr[: 'ep' HlA >>wr[3od3] >od:]+wr[: 'ep' HlA >> >

Degeneratesliceindicesarehandledgracefully:anindexthatistoolargeisreplacedbythe stringsize,anupperboundsmallerthanthelowerboundreturnsanemptystring.
>>wr[:0] >od110 'lA ep' >>wr[0] >od1: ' ' >>wr[:] >od21 ' ' >> >

Indicesmaybenegativenumbers,tostartcountingfromtheright.Forexample:
>>wr[1hatcaatr >od]#Telshrce '' A >>wr[2hatbtoecaatr >od]#Telsunhrce '' p >>wr[2]hattocaatr >od:#Telswhrces 'A p' >>wr[]vrtigecphattocaatr >od:2#Eeyhnxettelswhrces 'e' Hl >> >

Butnotethat0isreallythesameas0,soitdoesnotcountfromtheright!
>>wr[0sneqas0 >od]#(ic0eul) '' H >> >

Outofrangenegativesliceindicesaretruncated,butdonttrythisforsingleelement(non slice)indices:
>>wr[10] >od0: 'ep' HlA >>wr[1]ro >od0#err Taeak(otrcnalls) rcbcmseetclat: Fl<ti>,ln,i ie"sdn"ie1n? >> >

docs.python.org/tutorial/introduction.html#using-python-as-a-calculator

6/12

11/07/12

3. An Informal Introduction to Python Python v2.7.3 documentation

Idxro:srnneufrne neErrtigidxotoag

One way to remember how slices work is to think of the indices as pointing between characters,withtheleftedgeofthefirstcharacternumbered0.Thentherightedgeofthe lastcharacterofastringofncharactershasindexn,forexample:
++++++ |H|e|l|p|A| ++++++ 012345 54321

Thefirstrowofnumbersgivesthepositionoftheindices0...5inthestringthesecondrow gives the corresponding negative indices. The slice from i to j consists of all characters betweentheedgeslabelediandj,respectively. For nonnegative indices, the length of a slice is the difference of the indices, if both are withinbounds.Forexample,thelengthof w r [ : ] o d 1 3 is2. Thebuiltinfunction l n ) e ( returnsthelengthofastring:
>>s='ueclfaiitcxildcos >sprairglsiepaioiu' >>lns >e() 3 4 >> >

Seealso: SequenceTypesstr,unicode,list,tuple,bytearray,buffer,xrange Strings, and the Unicode strings described in the next section, are examples of sequencetypes,andsupportthecommonoperationssupportedbysuchtypes. StringMethods Both strings and Unicode strings support a large number of methods for basic transformationsandsearching. StringFormatting Informationaboutstringformattingwith s r f r a ( isdescribedhere. t.omt) StringFormattingOperations TheoldformattingoperationsinvokedwhenstringsandUnicodestringsaretheleft operandofthe % operatoraredescribedinmoredetailhere.

3.1.3.UnicodeStrings
StartingwithPython2.0anewdatatypeforstoringtextdataisavailabletotheprogrammer: the Unicode object. It can be used to store and manipulate Unicode data (see http://www.unicode.org/)andintegrateswellwiththeexistingstringobjects,providingauto conversionswherenecessary.

docs.python.org/tutorial/introduction.html#using-python-as-a-calculator

7/12

11/07/12

3. An Informal Introduction to Python Python v2.7.3 documentation

Unicodehastheadvantageofprovidingoneordinalforeverycharacterineveryscriptused in modern and ancient texts. Previously, there were only 256 possible ordinals for script characters.Textsweretypicallyboundtoacodepagewhichmappedtheordinalstoscript characters.Thisleadtoverymuchconfusionespeciallywithrespecttointernationalization (usually written as i 8 ' ' + 18 characters + ' ' of software. Unicode solves these 1n i n ) problemsbydefiningonecodepageforallscripts. CreatingUnicodestringsinPythonisjustassimpleascreatingnormalstrings:
>>uHloWrd! >'elol' uHloWrd! 'elol' >> >

Thesmall ' ' u infrontofthequoteindicatesthataUnicodestringissupposedtobecreated. If you want to include special characters in the string, you can do so by using the Python UnicodeEscapeencoding.Thefollowingexampleshowshow:
>>uHlou00ol' >'el\02Wrd! uHloWrd! 'elol' >> >

Theescapesequence \ 0 2 indicatestoinserttheUnicodecharacterwiththeordinalvalue u00 0x0020(thespacecharacter)atthegivenposition. OthercharactersareinterpretedbyusingtheirrespectiveordinalvaluesdirectlyasUnicode ordinals.If you have literal strings in the standard Latin1 encoding that is used in many Westerncountries,youwillfinditconvenientthatthelower256charactersofUnicodeare thesameasthe256charactersofLatin1. Forexperts,thereisalsoarawmodejustliketheonefornormalstrings.Youhavetoprefix the opening quote with ur to have Python use the RawUnicodeEscape encoding. It will onlyapplytheabove \ X X conversionifthereisanunevennumberofbackslashesinfront uXX ofthesmallu.
>>u'el\02Wrd! >rHlou00ol' uHloWrd! 'elol' >>u'el\u00ol' >rHlo\02Wrd! uHlo\\02Wrd! 'el\\u00ol' >> >

The raw mode is most useful when you have to enter lots of backslashes, as can be necessaryinregularexpressions. Apartfromthesestandardencodings,Pythonprovidesawholesetofotherwaysofcreating Unicodestringsonthebasisofaknownencoding. Thebuiltinfunction u i o e ) n c d ( providesaccesstoallregisteredUnicodecodecs(COders andDECoders).Someofthemorewellknownencodingswhichthesecodecscanconvert areLatin1,ASCII,UTF8,andUTF16.Thelattertwoarevariablelengthencodingsthat storeeachUnicodecharacterinoneormorebytes.Thedefaultencodingisnormallysetto ASCII, which passes through characters in the range 0 to 127 and rejects any other characterswithanerror.WhenaUnicodestringisprinted,writtentoafile,orconvertedwith

docs.python.org/tutorial/introduction.html#using-python-as-a-calculator

8/12

11/07/12

3. An Informal Introduction to Python Python v2.7.3 documentation

sr) t ( ,conversiontakesplaceusingthisdefaultencoding.

>> > >>uac >"b" uac 'b' >>sruac) >t("b" 'b' ac >>u >"" u\e\f\f' 'x4x6xc >>sru) >t("" Taeak(otrcnalls) rcbcmseetclat: Fl<ti>,ln,i ie"sdn"ie1n? Uioenoero:'si'cdccntecdhrcesioiin02riao ncdEcdErracioea'noecaatrnpsto:odnlnt

ToconvertaUnicodestringintoan8bitstringusingaspecificencoding,Unicodeobjects providean e c d ( methodthattakesoneargument,thenameoftheencoding.Lowercase noe) namesforencodingsarepreferred.


>>u.noe't' >""ecd(uf8) 'x3x4x3x6x3xc \c\a\c\b\c\b' >> >

IfyouhavedatainaspecificencodingandwanttoproduceacorrespondingUnicodestring fromit,youcanusethe u i o e ) n c d ( functionwiththeencodingnameasthesecondargument.


>>uioe'x3x4x3x6x3xc,'t' >ncd(\c\a\c\b\c\b'uf8) u\e\f\f' 'x4x6xc >> >

3.1.4.Lists
Pythonknowsanumberofcompounddatatypes,usedtogrouptogetherothervalues.The mostversatileisthelist,whichcanbewrittenasalistofcommaseparatedvalues(items) betweensquarebrackets.Listitemsneednotallhavethesametype.
>>a=[sa'eg'0,13] >'pm,'gs,1024 >>a > [sa'eg'0,13] 'pm,'gs,1024 >> >

Likestringindices,listindicesstartat0,andlistscanbesliced,concatenatedandsoon:
>>a0 >[] 'pm sa' >>a3 >[] 13 24 >>a] >[2 10 0 >>a1] >[:1 [eg'0] 'gs,10 >>a:]+[bcn,22 >[2'ao'*] [sa'eg'bcn,4 'pm,'gs,'ao'] >>3a:]+[Bo' >*[3'o!] [sa'eg'0,'pm,'gs,10sa'eg'0,'o!] 'pm,'gs,10sa'eg'0,'pm,'gs,10Bo' >> >

docs.python.org/tutorial/introduction.html#using-python-as-a-calculator

9/12

11/07/12

3. An Informal Introduction to Python Python v2.7.3 documentation

Allsliceoperationsreturnanewlistcontainingtherequestedelements.Thismeansthatthe followingslicereturnsashallowcopyofthelista:
>>a: >[] [sa'eg'0,13] 'pm,'gs,1024 >> >

Unlikestrings,whichareimmutable,itispossibletochangeindividualelementsofalist:
>>a > [sa'eg'0,13] 'pm,'gs,1024 >>a2[]+2 >[]=a23 >>a > [sa'eg'2,13] 'pm,'gs,1324 >> >

Assignmenttoslicesisalsopossible,andthiscanevenchangethesizeofthelistorclearit entirely:
>>#Rpaesmtm: >elcoeies ..a0212 .[:]=[,1] >>a > [,1,1324 122,13] >>#Rmvoe >eoesm: ..a02] .[:]=[ >>a > [2,13] 1324 >>#Isroe >netsm: ..a11'lth,'yz' .[:]=[bec'xzy] >>a > [2,'lth,'yz'24 13bec'xzy,13] >>#Isracpftefaheinn >net(oyo)islttebgnig >>a:]=a >[0 >>a > [2,'lth,'yz'242,'lth,'yz'24 13bec'xzy,13,13bec'xzy,13] >>#Certels:rpaealieswtnepyls >lahitelcltmihamtit >>a:] >[]=[ >>a > [ ] >> >

Thebuiltinfunction l n ) e ( alsoappliestolists:
>>a=[a,''c,'' >''b,''d] >>lna >e() 4 >> >

Itispossibletonestlists(createlistscontainingotherlists),forexample:
>>q=[,3 >2] >>p=[,q] >1,4 >>lnp >e() 3 >>p1 >[] [,3 2] >>p1[] >[]0 2 >>p1.ped'ta)#Sescin51 >[]apn(xr'eeto. >>p > >> >

docs.python.org/tutorial/introduction.html#using-python-as-a-calculator

10/12

11/07/12

3. An Informal Introduction to Python Python v2.7.3 documentation

[,[,3xr',4 12,'ta]] >>q > [,3xr' 2,'ta]

Notethatinthelastexample, p 1 and q [] reallyrefertothesameobject!Wellcomebackto objectsemanticslater.

3.2.FirstStepsTowardsProgramming
Ofcourse,wecanusePythonformorecomplicatedtasksthanaddingtwoandtwotogether. Forinstance,wecanwriteaninitialsubsequenceoftheFibonacciseriesasfollows:
>>#Fbncisre: >ioaceis ..#tesmowlmnsdfnstenx .huftoeeeteiehet ..a,1 .,b=0 >>wieb<1: >hl0 ..pitb .rn ..a,ab .,b=b+ .. . 1 1 2 3 5 8 >> >

Thisexampleintroducesseveralnewfeatures. Thefirstlinecontainsamultipleassignment:thevariables a and b simultaneouslyget the new values 0 and 1. On the last line this is used again, demonstrating that the expressions on the righthand side are all evaluated first before any of the assignmentstakeplace.Therighthandsideexpressionsareevaluatedfromtheleftto theright. The w i e loop executes as long as the condition (here: b 1 ) remains true. In hl < 0 Python,likeinC,anynonzerointegervalueistruezeroisfalse.Theconditionmay alsobeastringorlistvalue,infactanysequenceanythingwithanonzerolengthis true, empty sequences are false. The test used in the example is a simple comparison.ThestandardcomparisonoperatorsarewrittenthesameasinC: < (less than), > (greaterthan), = (equalto), < (lessthanorequalto), > (greaterthanorequal = = = to)and ! (notequalto). = Thebodyoftheloopisindented:indentationisPythonswayofgroupingstatements. Attheinteractiveprompt,youhavetotypeataborspace(s)foreachindentedline.In practice you will prepare more complicated input for Python with a text editor all decent text editors have an autoindent facility. When a compound statement is enteredinteractively,itmustbefollowedbyablanklinetoindicatecompletion(since theparsercannotguesswhenyouhavetypedthelastline).Notethateachlinewithina basicblockmustbeindentedbythesameamount.

docs.python.org/tutorial/introduction.html#using-python-as-a-calculator

11/12

11/07/12

3. An Informal Introduction to Python Python v2.7.3 documentation

The p i t r n statementwritesthevalueoftheexpression(s)itisgiven.Itdiffersfromjust writingtheexpressionyouwanttowrite(aswedidearlierinthecalculatorexamples) in the way it handles multiple expressions and strings. Strings are printed without quotes,andaspaceisinsertedbetweenitems,soyoucanformatthingsnicely,like this:
>>i=2626 >5*5 >>pit'haufii' >rnTevleos,i Tevleos656 haufii53 >> >

Atrailingcommaavoidsthenewlineaftertheoutput:
>>a,1 >,b=0 >>wieb<10: >hl00 ..pitb .rn, ..a,ab .,b=b+ .. . 1123581135843718 324591423376097 >> >

Notethattheinterpreterinsertsanewlinebeforeitprintsthenextpromptifthelastline wasnotcompleted.

docs.python.org/tutorial/introduction.html#using-python-as-a-calculator

12/12

You might also like