Вы находитесь на странице: 1из 99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

NonProgrammer'sTutorialforPython2.6/Printversion

Authors
JoshCogliati User:Jrincayc,jjcogliatijan2007ATyahoo.com

Contributors
KiahMorante(User:greenmanwitch) ElizabethCogliati JamesA.Brown JoeOppegaard BenjaminHell(User:Siebengang)

Frontmatter
AllexamplePythonsourcecodeinthistutorialisgrantedtothepublicdomain.Thereforeyoumaymodifyitandrelicenseitunderanylicenseyouplease. Sinceyouareexpectedtolearnprogramming,theGNUFreeDocumentationLicensewouldrequireyoutokeepallprogramsthatarederivedfromthesource codeinthistutorialunderthatlicense.Sincethepythonsourcecodeisgrantedtothepublicdomain,thatrequirementiswaived. ThistutorialwasoriginallywritteninLaTeXandwasavailableat:http://www.honors.montana.edu/~jjc/easytut/.Itwasmovedherebecausetheotherserveris goingawayanditwasbeingreadatleasttentimesaday.ThisdocumentisavailableasLaTeX,HTML,PDF,andPostscript.Goto http://jjc.freeshell.org/easytut/(Alsocouldtryhttp://web.archive.org/web/*/http://www.honors.montana.edu/~jjc/easytut/or http://www.geocities.com/jrincayc/easytut.tar.gz)toseealltheseforms.TherearealsoversionsofthisinKorean,Spanish,ItalianandGreekinthetarfile.

en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version

The NonProgrammers'TutorialForPythonisatutorialdesignedtobeanintroductiontothePythonprogramminglanguage.Thisguideisforsomeonewith

1/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

The NonProgrammers'TutorialForPythonisatutorialdesignedtobeanintroductiontothePythonprogramminglanguage.Thisguideisforsomeonewith noprogrammingexperience. IfyouhaveprogrammedinotherlanguagesIrecommendusingPythonTutorialforProgrammers(http://docs.python.org/tutorial/)writtenbyGuidovan Rossum. IfyouhaveanyquestionsorcommentspleaseusethediscussionpagesorseeNonProgrammer'sTutorialforPython2.6/Authorsforauthorcontact information.Iwelcomequestionsandcommentsaboutthistutorial.IwilltrytoansweranyquestionsyouhaveasbestIcan. ThanksgotoJamesA.BrownforwritingmostoftheWindowsinstallinfo.ThanksalsotoElizabethCogliatiforcomplainingenough:)abouttheoriginal tutorial(thatisalmostunusableforanonprogrammer),forproofreading,andformanyideasandcommentsonit.ThankstoJoeOppegaardforwritingalmost alltheexercises.ThankstoeveryoneIhavemissed.

Otherresources
PythonHomePage(http://www.python.org) PythonDocumentation(http://www.python.org/doc/) PythonTutorialforProgrammers(http://www.python.org/doc/current/tut/tut.html) LaTeX,PDF,andPostscript,andZipversions(http://www.honors.montana.edu/~jjc/easytut/) SeealsochapterTheEndforsomemorecomments.

Intro
Firstthingsfirst
So,you'veneverprogrammedbefore.Aswegothroughthistutorial,Iwillattempttoteachyouhowtoprogram.Therereallyisonlyonewaytolearnto program. Youmustread codeandwrite code(ascomputerprogramsareoftencalled).I'mgoingtoshowyoulotsofcode.YoushouldtypeincodethatI showyoutoseewhathappens.Playaroundwithitandmakechanges.Theworstthatcanhappenisthatitwon'twork.WhenItypeincodeitwillbe formattedlikethis:
# # P y t h o ni se a s yt ol e a r n p r i n t" H e l l o ,W o r l d ! "

That'ssoitiseasytodistinguishfromtheothertext.Ifyou'rereadingthisontheweb,you'llnoticethecodeisincolorthat'sjusttomakeitstandout,andto makethedifferentpartsofthecodestandoutfromeachother.Thecodeyouenterwillprobablynotbecolored,orthecolorsmaybedifferent,butitwon't affectthecodeaslongasyouenteritthesamewayasit'sprintedhere. Ifthecomputerprintssomethingoutitwillbeformattedlikethis:


H e l l o ,W o r l d !

en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version

2/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

(Notethatprintedtextgoestoyourscreen,anddoesnotinvolvepaper.Beforecomputershadscreens,theoutputofcomputerprogramswouldbeprintedon paper.) Ifyoutrythisprogramoutandyougetasyntaxerror,checkandseewhatversionofpythonyouhave.Ifyouhavepython3.0,youshouldbeusingtheNon Programmer'sTutorialforPython3.0.ThisarticlewasmadeforPython2.6 Therewilloftenbeamixtureofthetextyoutype(whichisshownin bold)andthetexttheprogramprintstothescreen,whichwouldlooklikethis:


H a l t ! W h oG o e st h e r e ?J o s h Y o um a yp a s s ,J o s h

(Someofthetutorialhasnotbeenconvertedtothisformat.Sincethisisawiki,youcanconvertitwhenyoufindit.) Iwillalsointroduceyoutotheterminologyofprogrammingforexample,thatprogrammingisoftenreferredtoas coding.Thiswillnotonlyhelpyou understandwhatprogrammersaretalkingabout,butalsohelpthelearningprocess. Now,ontomoreimportantthings.InordertoprograminPythonyouneedthePythonsoftware.Ifyoudon'talreadyhavethePythonsoftwaregoto http://www.python.org/download/andgettheproperversionforyourplatform.Downloadit,readtheinstructionsandgetitinstalled.

InstallingPython
ForPythonprogrammingyouneedaworkingPythoninstallationandatexteditor.Pythoncomeswithitsowneditor IDLE ,whichisquiteniceandtotally sufficientforthebeginning.Asyougetmoreintoprogramming,youwillprobablyswitchtosomeothereditorlike emacs, vioranother. ThePythondownloadpageishttp://www.python.org/download.Themostrecentversionis3.1,butany Python2.xversionsince2.2willworkforthistutorial. Becarefulwiththeupcoming Python3,though,assomemajordetailswillchangeandbreakthistutorial'sexamples.AversionofthistutorialforPython3is atNonProgrammer'sTutorialforPython3.Therearevariousdifferentinstallationfilesfordifferentcomputerplatformsavailableonthedownloadsite.Here aresomespecificinstructionsforthemostcommonoperatingsystems: Linux,BSDandUnixusers YouareprobablyluckyandPythonisalreadyinstalledonyourmachine.Totestittype p y t h o n onacommandline.Ifyouseesomethinglikethatinthe followingsection,youareset. IfyouhavetoinstallPython,justusetheoperatingsystem'spackagemanagerorgototherepositorywhereyourpackagesareavailableandgetPython. Alternatively,youcancompilePythonfromscratchafterdownloadingthesourcecode.IfyougetthesourcecodemakesureyoucompileintheTkextensionif youwanttouseIDLE. Macusers

en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version

StartingfromMacOSX(Tiger),Pythonshipsbydefaultwiththeoperatingsystem,butyoumightwanttoupdatetothenewerversion(checktheversionby

3/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

StartingfromMacOSX(Tiger),Pythonshipsbydefaultwiththeoperatingsystem,butyoumightwanttoupdatetothenewerversion(checktheversionby starting p y t h o n inacommandlineterminal).AlsoIDLE(thePythoneditor)mightbemissinginthestandardinstallation.Ifyouwantto(re)installPython,have alookattheMacpageonthePythondownloadsite(http://www.python.org/download/mac/). Windowsusers SomecomputermanufacturerspreinstallPython.Tocheckifyoualreadyhaveitinstalled,opencommandprompt(cmdinrunmenu)orMSDOSandtype python.Ifitsays"Badcommandorfilename"youwillneedtodownloadtheappropriateWindowsinstaller(thenormalone,ifyoudonothavea64bitAMD orIntelchip).Starttheinstallerbydoubleclickingitandfollowtheprocedure.Pythonforwindowscanbedownloadedfromtheofficialsiteofpython (http://www.python.org/getit/)

InteractiveMode
GointoIDLE(alsocalledthePythonGUI).Youshouldseeawindowthathassometextlikethis:
P y t h o n2 . 5 . 1( r 2 5 1 : 5 4 8 6 3 ,A p r1 82 0 0 7 ,0 8 : 5 1 : 0 8 )[ M S Cv . 1 3 1 03 2b i t( I n t e l ) ]o nw i n 3 2 T y p e" c o p y r i g h t " ," c r e d i t s "o r" l i c e n s e ( ) "f o rm o r ei n f o r m a t i o n .

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * P e r s o n a lf i r e w a l ls o f t w a r em a yw a r na b o u tt h ec o n n e c t i o nI D L E m a k e st oi t ss u b p r o c e s su s i n gt h i sc o m p u t e r ' si n t e r n a ll o o p b a c k i n t e r f a c e . T h i sc o n n e c t i o ni sn o tv i s i b l eo na n ye x t e r n a l i n t e r f a c ea n dn od a t ai ss e n tt oo rr e c e i v e df r o mt h eI n t e r n e t . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

I D L E1 . 2 . 1 > > >

The > > > isPython'swayoftellingyouthatyouareininteractivemode.Ininteractivemodewhatyoutypeisimmediatelyrun.Trytyping 1 + 1 in.Pythonwill respondwith 2 .InteractivemodeallowsyoutotestoutandseewhatPythonwilldo.IfyoueverfeelyouneedtoplaywithnewPythonstatements,gointo interactivemodeandtrythemout.

CreatingandRunningPrograms
GointoIDLEifyouarenotalready.Inthemenuatthetop,select F i l e then N e wW i n d o w .Inthenewwindowthatappears,typethefollowing:
p r i n t" H e l l o ,W o r l d ! "

Nowsavetheprogram:select F i l e fromthemenu,then S a v e .Saveitas" h e l l o . p y "(youcansaveitinanyfolderyouwant).Nowthatitissaveditcanberun.

Nextruntheprogrambygoingto R u n then R u nM o d u l e (orifyouhaveaolderversionofIDLEuse E d i t then R u ns c r i p t ).Thiswilloutput H e l l o ,W o r l d ! onthe * P y t h o n en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 4/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

Nextruntheprogrambygoingto R u n then R u nM o d u l e (orifyouhaveaolderversionofIDLEuse E d i t then R u ns c r i p t ).Thiswilloutput H e l l o ,W o r l d ! onthe * P y t h o n S h e l l * window. ForamoreindepthintroductiontoIDLE,alongertutorialwithscreenshotscanbefoundathttp://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html RunningPythonProgramsinUnix IfyouareusingUnix(suchasLinux,MacOSX,orBSD),ifyoumaketheprogramexecutablewith c h m o d ,andhaveasthefirstline:
# ! / u s r / b i n / e n vp y t h o n 2

youcanrunthepythonprogramwith . / h e l l o . p y likeanyothercommand. Note:Insomecomputerenvironments,youneedtowrite:


# ! / u s r / b i n / e n vp y t h o n

ExampleforSolaris:
# ! / u s r / b i n / p y t h o n

Programfilenames ItisveryusefultosticktosomerulesregardingthefilenamesofPythonprograms.Otherwisesomethings might gowrongunexpectedly.Thesedon'tmatter asmuchforprograms,butyoucanhaveweirdproblemsifyoudon'tfollowthemformodulenames(moduleswillbediscussedlater). 1. Alwayssavetheprogramwiththeextension . p y .Donotputanotherdotsomewhereelseinthefilename. 2. Onlyusestandardcharactersforfilenames:letters,numbers,dash()andunderscore(_ ). 3. Whitespace("")shouldnotbeusedatall(e.g.useunderscoresinstead). 4. Donotuseanythingotherthanaletter(particularlynonumbers!)atthebeginningofafilename. 5. Donotuse"nonenglish"characters(suchas , , , or )inyourfilenames,or,evenbetter,donotusethematallwhenprogramming.

UsingPythonfromthecommandline
Ifyoudon'twanttousePythonfromthecommandline,youdon'thaveto,justuseIDLE.Togetintointeractivemodejusttype p y t h o n withoutanyarguments. Torunaprogram,createitwithatexteditor(EmacshasagoodPythonmode)andthenrunitwith p y t h o np r o g r a m _ n a m e . Additionally,tousePythonwithinVim,youmaywanttovisitUsingvimasaPythonIDE(http://www.ibiblio.org/obp/pybiblio/tips/elkner/vim4python.php)

en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version

5/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

Wheretogethelp
AtsomepointinyourPythoncareeryouwillprobablygetstuckandhavenoclueabouthowtosolvetheproblemyouaresupposedtoworkon.Thistutorial onlycoversthebasicsofPythonprogramming,butthereisalotoffurtherinformationavailable. Pythondocumentation Firstofall,Pythonisverywelldocumented.Theremightevenbecopiesofthesedocumentsonyourcomputer,whichcamewithyourPythoninstallation: * TheofficialPythonTutorial(http://docs.python.org/tut/tut.html)byGuidovanRossumisoftenagoodstartingpointforgeneralquestions. Forquestionsaboutstandardmodules(youwilllearnwhatthisislater),thePythonLibraryReference(http://docs.python.org/lib/lib.html)istheplaceto look. Ifyoureallywanttogettoknowsomethingaboutthedetailsofthelanguage,thePythonReferenceManual(http://docs.python.org/ref/ref.html)is comprehensivebutquitecomplexforbeginners. Pythonusercommunity TherearealotofotherPythonusersoutthere,andusuallytheyareniceandwillingtohelpyou.Thisveryactiveusercommunityisorganisedmostlythrough mailinglistsandanewsgroup: Thetutormailinglist(http://mail.python.org/mailman/listinfo/tutor)isforfolkswhowanttoaskquestionsregardinghowtolearncomputerprogramming withthePythonlanguage. Thepythonhelpmailinglist(http://www.python.org/community/lists/#pythonhelp)ispython.org'shelpdesk.Youcanaskagroupofknowledgeable volunteersquestionsaboutallyourPythonproblems. ThePythonnewsgroupcomp.lang.python(news:comp.lang.python)(Googlegroupsarchive(http://groups.google.com/group/comp.lang.python/))isthe placeforgeneralPythondiscussions,questionsandthecentralmeetingpointofthecommunity. Inordernottoreinventthewheelanddiscussthesamequestionsagainandagain,peoplewillappreciateverymuchifyou doawebsearchforasolutionto yourproblembeforecontactingtheselists!

Hello,World
Whatyoushouldknow
YoushouldknowhowtoeditprogramsinatexteditororIDLE,savethefileandrunthefileoncethefileshavebeensavedtoyourdisk.

Printing
Programmingtutorialssincethebeginningoftimehavestartedwithalittleprogramcalled"Hello,World!" [1]ThesyntaxchangedinPython3.0.Ifyouare usingPython3.0,youshouldbereadingNonProgrammer'sTutorialforPython3instead.SohereisthePython2.6example:
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 6/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

p r i n t" H e l l o ,W o r l d ! "

Ifyouareusingthecommandlinetorunprogramsthentypeitinwithatexteditor,saveitas h e l l o . p y andrunitwith p y t h o nh e l l o . p y OtherwisegointoIDLE,createanewwindow,andcreatetheprogramasinsectionCreatingandRunningPrograms. Whenthisprogramisrunhere'swhatitprints:


H e l l o ,W o r l d !

NowI'mnotgoingtotellyouthiseverytime,butwhenIshowyouaprogramIrecommendthatyoutypeitinandrunit.IlearnbetterwhenItypeitinandyou probablydotoo. Nowhereisamorecomplicatedprogram:


p r i n t" J a c ka n dJ i l lw e n tu pah i l l " p r i n t" t of e t c hap a i lo fw a t e r ; " p r i n t" J a c kf e l ld o w n ,a n db r o k eh i sc r o w n , " p r i n t" a n dJ i l lc a m et u m b l i n ga f t e r . "

Whenyourunthisprogramitprintsout:
J a c ka n dJ i l lw e n tu pah i l l t of e t c hap a i lo fw a t e r ; J a c kf e l ld o w n ,a n db r o k eh i sc r o w n , a n dJ i l lc a m et u m b l i n ga f t e r .

Whenthecomputerrunsthisprogramitfirstseestheline:
p r i n t" J a c ka n dJ i l lw e n tu pah i l l "

sothecomputerprints:
J a c ka n dJ i l lw e n tu pah i l l

Thenthecomputergoesdowntothenextlineandsees:
p r i n t" t of e t c hap a i lo fw a t e r ; "

en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version

7/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

Sothecomputerprintstothescreen:
t of e t c hap a i lo fw a t e r ;

Thecomputerkeepslookingateachline,followsthecommandandthengoesontothenextline.Thecomputerkeepsrunningcommandsuntilitreachesthe endoftheprogram. Terminology Nowisprobablyagoodtimetogiveyouabitofanexplanationofwhatishappeningandalittlebitofprogrammingterminology. Whatweweredoingabovewasusinga commandcalled p r i n t .The p r i n t commandisfollowedbyoneormore arguments.Sointhisexample


p r i n t" H e l l o ,W o r l d ! "

thereisone argument ,whichis " H e l l o ,W o r l d ! " .Notethatthisargumentisagroupofcharactersenclosedindoublequotes(").Thisiscommonlyreferredtoas a stringofcharacters,or string,forshort.Anotherexampleofastringis " J a c ka n dJ i l lw e n tu pah i l l " . Acommandanditsargumentsarecollectivelyreferredtoasa statement ,so
p r i n t" H e l l o ,W o r l d ! "

isanexampleofastatement. That'sprobablymorethanenoughterminologyfornow.

Expressions
Hereisanotherprogram:
p r i n t" 2+2i s " ,2+2 p r i n t" 3*4i s " ,3*4 p r i n t" 1 0 0-1i s " ,1 0 0-1 p r i n t" ( 3 3+2 )/5+1 1 . 5i s " ,( 3 3+2 )/5+1 1 . 5

Andhereisthe output whentheprogramisrun:


2+2i s4 3*4i s1 2 1 0 0-1i s9 9 ( 3 3+2 )/5+1 1 . 5i s1 8 . 5
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 8/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

Asyoucansee,Pythoncanturnyoursixhundreddollarcomputerintoa2dollarcalculator. Inthisexample,theprintcommandisfollowedbytwoarguments,witheachoftheargumentsseparatedbyacomma.Sowiththefirstlineoftheprogram
p r i n t" 2+2i s " ,2+2

Thefirstargumentisthestring " 2+2i s " andthesecondargumentisthe mathematicalexpression 2+2 ,whichiscommonlyreferredtoasan expression. Whatisimportanttonoteisthatastringisprintedasis(thestringiswhatiswithinthedoublequotesbutdoesn'tincludethedoublequotesthemselves.So thestringisprintedwithouttheenclosingdoublequotes.)Butan expressionis evaluated,(inotherwords,converted)toitsactualvalue. Pythonhassixbasicoperationsfornumbers: Operation Symbol Example
5* *2= =2 5 2*3= =6 1 4/3= =4 1 4%3= =2 1+2= =3 4-3= =1

Power(exponentiation) * * Multiplication Division Remainder(modulo) Addition Subtraction


* / % + -

Noticethatdivisionfollowstherule, iftherearenodecimalstostartwith,therewillbenodecimalstoendwith.Thefollowingprogramshowsthis:
p r i n t" 1 4/3=" ,1 4/3 p r i n t" 1 4%3=" ,1 4%3 p r i n t p r i n t" 1 4 . 0/3 . 0= " ,1 4 . 0/3 . 0 p r i n t" 1 4 . 0%3 . 0= " ,1 4 . 0%3 . 0 p r i n t p r i n t" 1 4 . 0/3= " ,1 4 . 0/3 p r i n t" 1 4 . 0%3= " ,1 4 . 0%3 p r i n t p r i n t" 1 4/3 . 0= " ,1 4/3 . 0 p r i n t" 1 4%3 . 0= " ,1 4%3 . 0 p r i n t

Withtheoutput:
1 4/3=4
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 9/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

1 4%3=2 1 4 . 0/3 . 0=4 . 6 6 6 6 6 6 6 6 6 6 7 1 4 . 0%3 . 0=2 . 0 1 4 . 0/3=4 . 6 6 6 6 6 6 6 6 6 6 7 1 4 . 0%3=2 . 0 1 4/3 . 0=4 . 6 6 6 6 6 6 6 6 6 6 7 1 4%3 . 0=2 . 0

NoticehowPythongivesdifferentanswersforsomeproblemsdependingonwhetherornotdecimalvaluesareused. Theorderofoperationsisthesameasinmath: parentheses ( ) exponents * * multiplication * ,division / ,andremainder % addition + andsubtraction Souseparenthesestostructureyourformulaswhenneeded.

Talkingtohumans(andotherintelligentbeings)
Ofteninprogrammingyouaredoingsomethingcomplicatedandmaynotinthefuturerememberwhatyoudid.Whenthishappens,theprogramshould probablybecommented.A comment isanotetoyouandotherprogrammersexplainingwhatishappening.Forexample:
#N o tq u i t eP I ,b u ta ni n c r e d i b l es i m u l a t i o n p r i n t2 2 . 0/7 . 0 #3 5 5 / 1 1 3i se v e nm o r ei n c r e d i b l er a t i o n a la p p r o xt oP I

Whichoutputs
3 . 1 4 2 8 5 7 1 4 2 8 6

Noticethatthecommentstartswithahash: # .Commentsareusedtocommunicatewithotherswhoreadtheprogramandyourfutureselftomakeclearwhat iscomplicated. Notethatanytextcanfollowacomment,andthatwhentheprogramisrun,thetextafterthe # throughtotheendofthatlineisignored.The # doesnothave tobeatthebeginningofanewline:


#O u t p u tP Io nt h es c r e e n p r i n t2 2 . 0/7 . 0#W e l l ,j u s tag o o da p p r o x i m a t i o n
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 10/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

Examples
Eachchapter(eventually)willcontainexamplesoftheprogrammingfeaturesintroducedinthechapter.Youshouldatleastlookoverthemandseeifyou understandthem.Ifyoudon't,youmaywanttotypetheminandseewhathappens.Messaroundwiththem,changethemandseewhathappens. Denmark.py
p r i n t" S o m e t h i n g ' sr o t t e ni nt h es t a t eo fD e n m a r k . " p r i n t" -S h a k e s p e a r e "

Output:
S o m e t h i n g ' sr o t t e ni nt h es t a t eo fD e n m a r k . -S h a k e s p e a r e

School.py
#T h i si sn o tq u i t et r u eo u t s i d eo fU S A #a n di sb a s e do nm yd i mm e m o r i e so fm yy o u n g e ry e a r s p r i n t" F i r s tG r a d e " p r i n t" 1+1= " ,1+1 p r i n t" 2+4= " ,2+4 p r i n t" 5-2= " ,5-2 p r i n t p r i n t" T h i r dG r a d e " p r i n t" 2 4 3-2 3= " ,2 4 3-2 3 p r i n t" 1 2*4= " ,1 2*4 p r i n t" 1 2/3= " ,1 2/3 p r i n t" 1 3/3= " ,1 3/3 ," R " ,1 3%3 p r i n t p r i n t" J u n i o rH i g h " p r i n t" 1 2 3 . 5 6-6 2 . 1 2= " ,1 2 3 . 5 6-6 2 . 1 2 p r i n t" ( 4+3 )*2= " ,( 4+3 )*2 p r i n t" 4+3*2= " ,4+3*2 p r i n t" 3* *2= " ,3* *2 p r i n t

Output:
F i r s tG r a d e 1+1=2 2+4=6 5-2=3 T h i r dG r a d e 2 4 3-2 3=2 2 0
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 11/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

1 2*4=4 8 1 2/3=4 1 3/3=4R1 J u n i o rH i g h 1 2 3 . 5 6-6 2 . 1 2=6 1 . 4 4 ( 4+3 )*2=1 4 4+3*2=1 0 3* *2=9

Exercises
1. Writeaprogramthatprintsyourfullnameandyourbirthdayasseparatestrings. 2. Writeaprogramthatshowstheuseofall6mathfunctions.

Solution 1.Writeaprogramthatprintsyourfullnameandyourbirthdayasseparatestrings.

p r i n t" A d aL o v e l a c e " ," b o r no n " ," N o v e m b e r2 7 ,1 8 5 2 "

2.Writeaprogramthatshowstheuseofall6mathoperations.

# A n y t h i n ga l o n gt h e s el i n e si sa c c e p t a b l e : # A d d i t i o n p r i n t" 2+5=" ,2+5 # s u b t r a c t i o n p r i n t" 9-3=" ,9-3 # m u l t i p l i c a t i o n p r i n t" 3*3=" ,3*3 # d i v i s i o n p r i n t" 9 0/5=" ,9 0/5 # e x p o n e n t s p r i n t" 7t ot h ep o w e ro f2( s q u a r e d )=" ,7* *2

en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version

12/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

# r e m a i n d e r p r i n t" t h er e m a i n d e rw h e nd o i n g2 2/9=" ,2 2%9

Footnotes 1. Listof"Hello,world!"programsinmanyprogramminglanguages

WhoGoesThere?
InputandVariables
NowIfeelitistimeforareallycomplicatedprogram.Hereitis:
p r i n t" H a l t ! " u s e r _ r e p l y=r a w _ i n p u t ( " W h og o e st h e r e ?" ) p r i n t" Y o um a yp a s s , " ,u s e r _ r e p l y

When I ranit,hereiswhat myscreenshowed:


H a l t ! W h og o e st h e r e ?J o s h Y o um a yp a s s ,J o s h

Note:AfterrunningthecodebypressingF5,thePythonshellwillonlygiveoutput:
H a l t ! W h og o e st h e r e ?

YouneedtoenteryournameinthePythonshell,andthenpressEntertogettherestoftheoutput. Ofcoursewhenyouruntheprogramyourscreenwilllookdifferentbecauseofthe r a w _ i n p u t ( ) statement.Whenyourantheprogramyouprobablynoticed(you didruntheprogram,right?)thatyouhadtotypeinyournameandthenpressEnter.Thentheprogramprintedoutsomemoretextandalsoyourname.This isanexampleof input .Theprogramreachesacertainpointandthenwaitsfortheusertoinputsomedatathattheprogramcanuselater. Ofcourse,gettinginformationfromtheuserwouldbeuselessifwedidn'thaveanywheretoputthatinformationandthisiswherevariablescomein.Inthe previousprogram, u s e r _ r e p l y isa variable.Variablesarelikeaboxthatcanstoresomepieceofdata.Hereisaprogramtoshowexamplesofvariables:
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 13/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

a=1 2 3 . 4 b 2 3=' S p a m ' f i r s t _ n a m e=" B i l l " b=4 3 2 c=a+b p r i n t" a+bi s " , c p r i n t" f i r s t _ n a m ei s " , f i r s t _ n a m e p r i n t" S o r t e dP a r t s ,A f t e rM i d n i g h to r " , b 2 3

Andhereistheoutput:
a+bi s5 5 5 . 4 f i r s t _ n a m ei sB i l l S o r t e dP a r t s ,A f t e rM i d n i g h to rS p a m

Thevariablesintheaboveprogramare a , b 2 3 , f i r s t _ n a m e , b ,and c .AvariableinPythoncanstoreanytypeofdatainthisexamplewestoredsomestrings(e.g. "Bill")andsomenumbers(e.g.432). Notethedifferencebetweenstringsandvariablenames.Stringsaremarkedwithquotationmarks,whichtellsthecomputer"don'ttrytounderstand,justtake thistextasitis":


p r i n t" f i r s t _ n a m e "

Thiswouldprintthetext:
f i r s t _ n a m e

asis.Variablenamesarewrittenwithoutanyquotationmarksandinstructthecomputer"usethevalueI'vepreviouslystoredunderthisname":
p r i n tf i r s t _ n a m e

whichwouldprint(afterthepreviousexample):
B i l l

Assignment
Okay,sowehavetheseboxescalledvariablesandalsodatathatcangointothevariable.Thecomputerwillseealinelike f i r s t _ n a m e=" B i l l " anditreadsitas "Putthestring B i l l intothebox(orvariable) f i r s t _ n a m e .Lateronitseesthestatement c=a+b anditreadsitas"putthesumof a+b or 1 2 3 . 4+4 3 2 whichequals 5 5 5 . 4 into c ".Therighthandsideofthestatement(a+b )is evaluatedandtheresultisstoredinthevariableonthelefthandside(c ).Thisiscalled assignment ,
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 14/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

andyoushouldnotconfusetheassignmentequalsign(= )with"equality"inamathematicalsensehere(that'swhat = = willbeusedforlater). Hereisanotherexampleofvariableusage:


a=1 p r i n ta a=a+1 p r i n ta a=a*2 p r i n ta

Andofcoursehereistheoutput:
1 2 4

Evenifitisthesamevariableonbothsidesthecomputerstillreadsitas"Firstfindoutthedatatostoreandthenfindoutwherethedatagoes". OnemoreprogrambeforeIendthischapter:
n u m b e r=i n p u t ( " T y p ei nan u m b e r :" ) t e x t=r a w _ i n p u t ( " T y p ei nas t r i n g :" ) p r i n t" n u m b e r= " ,n u m b e r p r i n t" n u m b e ri sa " ,t y p e ( n u m b e r ) p r i n t" n u m b e r*2= " ,n u m b e r*2 p r i n t" t e x t= " ,t e x t p r i n t" t e x ti sa " ,t y p e ( t e x t ) p r i n t" t e x t*2= " ,t e x t*2

TheoutputIgotwas:
T y p ei naN u m b e r :1 2 . 3 4 T y p ei naS t r i n g :H e l l o n u m b e r=1 2 . 3 4 n u m b e ri sa< t y p e' f l o a t ' > n u m b e r*2=2 4 . 6 8 t e x t=H e l l o t e x ti sa< t y p e' s t r ' > t e x t*2=H e l l o H e l l o

Noticethat n u m b e r wasgottenwith i n p u t ( ) while t e x t wasgottenwith r a w _ i n p u t ( ) . r a w _ i n p u t ( ) returnsastringwhile i n p u t ( ) returnsanumber.Whenyouwantthe usertotypeinanumberuse i n p u t ( ) butifyouwanttheusertotypeinastringuse r a w _ i n p u t ( ) .

en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version

15/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

Thesecondhalfoftheprogramuses t y p e ( ) whichtellswhatavariableis.Numbersareoftype i n t or f l o a t ,whichareshortfor integerand floatingpoint (mostly usedfordecimalnumbers),respectively.Textstringsareoftype s t r ,shortfor string.Integersandfloatscanbeworkedonbymathematicalfunctions,strings cannot.Noticehowwhenpythonmultipliesanumberbyanintegertheexpectedthinghappens.Howeverwhenastringismultipliedbyanintegertheresultis thatmultiplecopiesofthestringareproduced(i.e., t e x t*2=H e l l o H e l l o ). Theoperationswithstringsdodifferentthingsthanoperationswithnumbers.Herearesomeinteractivemodeexamplestoshowthatsomemore.
> > >" T h i s "+""+" i s "+"j o i n e d . " ' T h i si sj o i n e d . ' > > >" H a ,"*5 ' H a ,H a ,H a ,H a ,H a ,' > > >" H a ,"*5+" h a ! " ' H a ,H a ,H a ,H a ,H a ,h a ! ' > > >

Thiscouldalsobedoneasaprogram:
p r i n t" T h i s "+""+" i s "+"j o i n e d . " p r i n t" H a ,"*5 p r i n t" H a ,"*5+" h a ! "

Hereisthelistofsomestringoperations: Operation Repetition Symbol


*

Example
" i "*5= =" i i i i i " " H e l l o ,"+" W o r l d ! "= =" H e l l o ,W o r l d ! "

Concatenation +

Examples
Rate_times.py
#T h i sp r o g r a mc a l c u l a t e sr a t ea n dd i s t a n c ep r o b l e m s p r i n t" I n p u tar a t ea n dad i s t a n c e " r a t e=i n p u t ( " R a t e :" ) d i s t a n c e=i n p u t ( " D i s t a n c e :" ) p r i n t" T i m e : " ,( d i s t a n c e/r a t e )

Sampleruns:
I n p u tar a t ea n dad i s t a n c e R a t e :5
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 16/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

D i s t a n c e :1 0 T i m e :2

I n p u tar a t ea n dad i s t a n c e R a t e :3 . 5 2 D i s t a n c e :4 5 . 6 T i m e :1 2 . 9 5 4 5 4 5 4 5 4 5

Area.py
#T h i sp r o g r a mc a l c u l a t e st h ep e r i m e t e ra n da r e ao far e c t a n g l e p r i n t" C a l c u l a t ei n f o r m a t i o na b o u tar e c t a n g l e " l e n g t h=i n p u t ( " L e n g t h :" ) w i d t h=i n p u t ( " W i d t h :" ) p r i n t" A r e a " ,l e n g t h*w i d t h p r i n t" P e r i m e t e r " ,2*l e n g t h+2*w i d t h

Sampleruns:
C a l c u l a t ei n f o r m a t i o na b o u tar e c t a n g l e L e n g t h :4 W i d t h :3 A r e a1 2 P e r i m e t e r1 4

C a l c u l a t ei n f o r m a t i o na b o u tar e c t a n g l e L e n g t h :2 . 5 3 W i d t h :5 . 2 A r e a1 3 . 1 5 6 P e r i m e t e r1 5 . 4 6

temperature.py
#C o n v e r t sF a h r e n h e i tt oC e l s i u s t e m p=i n p u t ( " F a h r e n h e i tt e m p e r a t u r e :" ) p r i n t( t e m p-3 2 . 0 )*5 . 0/9 . 0

Sampleruns:
F a h r e n h e i tt e m p e r a t u r e :3 2 0 . 0
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 17/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

F a h r e n h e i tt e m p e r a t u r e :4 0 4 0 . 0

F a h r e n h e i tt e m p e r a t u r e :2 1 2 1 0 0 . 0

F a h r e n h e i tt e m p e r a t u r e :9 8 . 6 3 7 . 0

Exercises
Writeaprogramthatgets2stringvariablesand2integervariablesfromtheuser,concatenates(joinsthemtogetherwithnospaces)anddisplaysthestrings, thenmultipliesthetwonumbersonanewline. Solution Writeaprogramthatgets2stringvariablesand2integervariablesfromtheuser,concatenates(joinsthemtogetherwithnospaces)anddisplaysthestrings, thenmultipliesthetwonumbersonanewline.

s t r i n g 1=r a w _ i n p u t ( ' S t r i n g1 :' ) s t r i n g 2=r a w _ i n p u t ( ' S t r i n g2 :' ) i n t 1=i n p u t ( ' I n t e g e r1 :' ) i n t 2=i n p u t ( ' I n t e g e r2 :' ) p r i n ts t r i n g 1+s t r i n g 2 p r i n ti n t 1*i n t 2

AnotherSolution

p r i n t" t h i si sa ne x e r c i s e " n u m b e r _ 1=i n p u t ( " p l e a s ei n p u tt h ef i r s tn u m b e r :" ) n u m b e r _ 2=i n p u t ( " P l e a s ei n p u tt h es e c o n dn u m b e r :" ) s t r i n g _ 1=r a w _ i n p u t ( " P l e a s ei n p u tt h ef i r s th a l fo ft h ew o r d :" ) s t r i n g _ 2=r a w _ i n p u t ( " p l e a s ei n p u tt h es e c o n dh a l fo ft h ew o r d :" ) p r i n t" t h ew o r dy o ui n p u ti s' "+s t r i n g _ 1+s t r i n g _ 2+" ' "
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 18/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

p r i n t" t h er e s u l to ft h e2n u m b e r si s : " ,n u m b e r _ 1*n u m b e r _ 2

Countto10
Whileloops
Herewepresentourfirst controlstructure.Ordinarilythecomputerstartswiththefirstlineandthengoesdownfromthere.Controlstructureschangetheorder thatstatementsareexecutedordecideifacertainstatementwillberun.Here'sthesourceforaprogramthatusesthe w h i l e controlstructure:
a=0 w h i l ea<1 0 : a=a+1 p r i n ta

Andhereistheextremelyexcitingoutput:
1 2 3 4 5 6 7 8 9 1 0

Andyouthoughtitcouldn'tgetanyworseafterturningyourcomputerintoafivedollarcalculator? Sowhatdoestheprogramdo?Firstitseestheline a=0 andsets a tozero.Thenitsees w h i l ea<1 0 : andsothecomputercheckstoseeif a<1 0 .Thefirsttime thecomputerseesthisstatement a iszerosoitislessthan10.Inotherwordsaslongas a islessthantenthecomputerwillrunthetabbedinstatements. Thiseventuallymakes a equaltoten(byaddingoneto a againandagain),andthe w h i l ea<1 0 isnottrueanylonger.Reachingthatpointtheprogramwillnot runtheindentedlinesanylonger. Alwaysremembertoputacolon":"afterthe"while"statement! Hereisanotherexampleoftheuseof w h i l e :
a=1 s=0 p r i n t' E n t e rN u m b e r st oa d dt ot h es u m . '
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 19/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

p r i n t' E n t e r0t oq u i t . ' w h i l ea! =0 : p r i n t' C u r r e n tS u m : ' ,s a=i n p u t ( ' N u m b e r ?' ) s=s+a p r i n t' T o t a lS u m= ' ,s

E n t e rN u m b e r st oa d dt ot h es u m . E n t e r0t oq u i t . C u r r e n tS u m :0 N u m b e r ?2 0 0 C u r r e n tS u m :2 0 0 N u m b e r ?1 5 . 2 5 C u r r e n tS u m :1 8 4 . 7 5 N u m b e r ?1 5 1 . 8 5 C u r r e n tS u m :3 2 . 9 N u m b e r ?1 0 . 0 0 C u r r e n tS u m :4 2 . 9 N u m b e r ?0 T o t a lS u m=4 2 . 9

Noticehow p r i n t' T o t a lS u m= ' ,s isonlyrunattheend.The w h i l e statementonlyaffectsthelinesthatareindentedwithwhitespace.The ! = means"doesnot equal"so " w h i l ea! =0 : " means:"until a iszero,runthetabbedstatementsthatfollow." Infiniteloops Nowthatwehavewhileloops,itispossibletohaveprogramsthatrunforever.Aneasywaytodothisistowriteaprogramlikethis:
w h i l e1= =1 : p r i n t" H e l p ,I ' ms t u c ki nal o o p . "

The" = = "operatorisusedtotestequalityoftheexpressionsonthetwosidesoftheoperator,justas" < "wasusedfor"lessthan"before(youwillgeta completelistofallcomparisonoperatorsinthenextchapter). Thisprogramwilloutput H e l p ,I ' ms t u c ki nal o o p . untiltheheatdeathoftheuniverseoruntilyoustopit,because1willforeverbeequalto1.Thewaytostopit istohittheControl(or Ctrl)buttonand C(theletter)atthesametime.Thiswillkilltheprogram.(Note:sometimesyouwillhavetohitenteraftertheControl C.)

Examples
Fibonacci.py
#T h i sp r o g r a mc a l c u l a t e st h eF i b o n a c c is e q u e n c e a=0
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 20/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

b=1 c o u n t=0 m a x _ c o u n t=2 0 w h i l ec o u n t<m a x _ c o u n t : c o u n t=c o u n t+1 #w en e e dt ok e e pt r a c ko fas i n c ew ec h a n g ei t o l d _ a=a o l d _ b=b a=o l d _ b b=o l d _ a+o l d _ b #N o t i c et h a tt h e,a tt h ee n do fap r i n ts t a t e m e n tk e e p si t #f r o ms w i t c h i n gt oan e wl i n e p r i n t ( o l d _ a ) ,

Output:
01123581 32 13 45 58 91 4 42 3 33 7 76 1 09 8 71 5 9 72 5 8 44 1 8 1

Notetheoutputonasinglelinebyuseofacommaattheendofthe p r i n t statement. Password.py


#W a i t su n t i lap a s s w o r dh a sb e e ne n t e r e d . U s eC o n t r o l Ct ob r e a ko u tw i t h o u t #t h ep a s s w o r d #N o t et h a tt h i sm u s tn o tb et h ep a s s w o r ds ot h a tt h e #w h i l el o o pr u n sa tl e a s to n c e . p a s s w o r d=" n op a s s w o r d " #n o t et h a t! =m e a n sn o te q u a l w h i l ep a s s w o r d! =" u n i c o r n " : p a s s w o r d=r a w _ i n p u t ( " P a s s w o r d :" ) p r i n t" W e l c o m ei n "

Samplerun:
P a s s w o r d :a u o P a s s w o r d :y 2 2 P a s s w o r d :p a s s w o r d P a s s w o r d :o p e ns e s a m e P a s s w o r d :u n i c o r n W e l c o m ei n

Exercises
WriteaprogramthataskstheuserforaLoginNameandpassword.Thenwhentheytype"lock",theyneedtotypeintheirnameandpasswordtounlockthe 21/99

en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

WriteaprogramthataskstheuserforaLoginNameandpassword.Thenwhentheytype"lock",theyneedtotypeintheirnameandpasswordtounlockthe program. Solution WriteaprogramthataskstheuserforaLoginNameandpassword.Thenwhentheytype"lock",theyneedtotypeintheirnameandpasswordtounlockthe program.

n a m e=r a w _ i n p u t ( " W h a ti sy o u rU s e r N a m e :" ) p a s s w o r d=r a w _ i n p u t ( " W h a ti sy o u rP a s s w o r d :" ) p r i n t" T ol o c ky o u rc o m p u t e rt y p el o c k . " c o m m a n d=" " i n p u t 1=" " i n p u t 2=" " w h i l ec o m m a n d! =" l o c k " : c o m m a n d=r a w _ i n p u t ( " W h a ti sy o u rc o m m a n d :" ) w h i l ei n p u t 1! =n a m e : i n p u t 1=r a w _ i n p u t ( " W h a ti sy o u ru s e r n a m e :" ) w h i l ei n p u t 2! =p a s s w o r d : i n p u t 2=r a w _ i n p u t ( " W h a ti sy o u rp a s s w o r d :" ) p r i n t" W e l c o m eb a c kt oy o u rs y s t e m ! "

Ifyouwouldliketheprogramtoruncontinuously,justadda w h i l e1= =1 : looparoundthewholething.Youwillhavetoindenttherestoftheprogramwhenyou addthisatthetopofthecode,butdon'tworry,youdon'thavetodoitmanuallyforeachline!Justhighlighteverythingyouwanttoindentandclickon"Indent" under"Format"inthetopbarofthepythonwindow.Notethatyoucanuseemptystringslikethis: " " . Anotherwayofdoingthiscouldbe:

n a m e=r a w _ i n p u t ( ' S e tn a m e :' ) p a s s w o r d=r a w _ i n p u t ( ' S e tp a s s w o r d :' ) w h i l e1= =1 : n a m e g u e s s = p a s s w o r d g u e s s = k e y = " " #m u l t i p l ea s s i g n m e n t w h i l e( n a m e g u e s s! =n a m e )o r( p a s s w o r d g u e s s! =p a s s w o r d ) : n a m e g u e s s=r a w _ i n p u t ( ' N a m e ?' ) p a s s w o r d g u e s s=r a w _ i n p u t ( ' P a s s w o r d ?' ) p r i n t" W e l c o m e , " ,n a m e ," .T y p el o c kt ol o c k . " w h i l ek e y! =" l o c k " : k e y=r a w _ i n p u t ( " " )

Noticethe o r inwhile ( n a m e! =" u s e r " )o r( p a s s w o r d! =" p a s s " ) : ,whichwehaven'tyetintroduced.Youcanprobablyfigureouthowitworks.

en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version

22/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

l o g i n=" j o h n " p a s s w o r d=" t u c k e r " l o g g e d = 2 w h i l el o g g e d! =0 : w h i l el o g i n! =" P h i l " : l o g i n=r a w _ i n p u t ( " L o g i n:" ) w h i l ep a s s w o r d! =" M c C h i c k e n " : p a s s w o r d=r a w _ i n p u t ( " P a s s w o r d :" ) l o g g e d=1 p r i n t" W e l c o m e ! " p r i n t" T ol e a v et y p el o c k" w h i l el o g g e d= =1 : l e a v e=r a w _ i n p u t( " > >" ) i fl e a v e= =" l o c k " : l o g g e d=0 p r i n t" G o o d b y e ! ! "

Thismethod,althoughabitmorecrudealsoworks.Noticeitusestheasofyetunintroduced i f function.

Decisions
Ifstatement
AsalwaysIbelieveIshouldstarteachchapterwithawarmuptypingexercise,sohereisashortprogramtocomputetheabsolutevalueofanumber:
n=i n p u t ( " N u m b e r ?" ) i fn<0 : p r i n t" T h ea b s o l u t ev a l u eo f " ,n ," i s " ,n e l s e : p r i n t" T h ea b s o l u t ev a l u eo f " ,n ," i s " ,n

HereistheoutputfromthetwotimesthatIranthisprogram:
N u m b e r ?3 4 T h ea b s o l u t ev a l u eo f3 4i s3 4

N u m b e r ?1 T h ea b s o l u t ev a l u eo f1i s1

en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version

23/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

Sowhatdoesthecomputerdowhenitseesthispieceofcode?Firstitpromptstheuserforanumberwiththestatement" n=i n p u t ( " N u m b e r ?" ) ".Nextitreads theline" i fn<0 : ".If n islessthanzeroPythonrunstheline" p r i n t" T h ea b s o l u t ev a l u eo f " ,n ," i s " ,n ".Otherwiseitrunstheline" p r i n t" T h ea b s o l u t ev a l u eo f " ,n , " i s " ,n ". MoreformallyPythonlooksatwhetherthe expression n<0 istrueorfalse.An i f statementisfollowedbyanindented blockofstatementsthatarerunwhen theexpressionistrue.Optionallyafterthe i f statementisan e l s e statementandanotherindented blockofstatements.Thissecondblockofstatementsisrun iftheexpressionisfalse. Thereareanumberofdifferentteststhatanexpressioncanhave.Hereisatableofallofthem: operator
< < = > > = = = ! = < >

function lessthan lessthanorequalto greaterthan greaterthanorequalto equal notequal anotherwaytosaynotequal(oldstyle,notrecommended)

Anotherfeatureofthe i f commandisthe e l i f statement.Itstandsforelseifandmeansiftheoriginal i f statementisfalsebutthe e l i f partistrue,thendo the e l i f part.Andifneitherthe i f or e l i f expressionsaretrue,thendowhat'sinthe e l s e block.Here'sanexample:


a=0 w h i l ea<1 0 : a=a+1 i fa>5 : p r i n ta ," > " ,5 e l i fa< =7 : p r i n ta ," < = " ,7 e l s e : p r i n t" N e i t h e rt e s tw a st r u e "

andtheoutput:
1< =7 2< =7 3< =7 4< =7 5< =7 6>5 7>5
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 24/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

8>5 9>5 1 0>5

Noticehowthe e l i fa< =7 isonlytestedwhenthe i f statementfailstobetrue.Therecanbemorethanone e l i f expression,allowingmultipleteststobedone inasingle i f statement.

Examples
#T h i sP r o g r a mD e m o n s t r a t e st h eu s eo ft h e= =o p e r a t o r #u s i n gn u m b e r s p r i n t5= =6 #U s i n gv a r i a b l e s x=5 y=8 p r i n tx= =y

Andtheoutput
F a l s e F a l s e

High_low.py
#P l a y st h eg u e s s i n gg a m eh i g h e ro rl o w e r #T h i ss h o u l da c t u a l l yb es o m e t h i n gt h a ti ss e m ir a n d o ml i k et h e #l a s td i g i t so ft h et i m eo rs o m e t h i n ge l s e ,b u tt h a tw i l lh a v et o #w a i tt i l lal a t e rc h a p t e r . ( E x t r aC r e d i t ,m o d i f yi tt ob er a n d o m #a f t e rt h eM o d u l e sc h a p t e r ) n u m b e r=7 8 g u e s s=0 w h i l eg u e s s! =n u m b e r : g u e s s=i n p u t ( " G u e s san u m b e r :" ) i fg u e s s>n u m b e r : p r i n t" T o oh i g h " e l i fg u e s s<n u m b e r : p r i n t" T o ol o w " p r i n t" J u s tr i g h t "

Samplerun:
G u e s san u m b e r :1 0 0
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 25/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

T o oh i g h G u e s san u m b e r :5 0 T o ol o w G u e s san u m b e r :7 5 T o ol o w G u e s san u m b e r :8 7 T o oh i g h G u e s san u m b e r :8 1 T o oh i g h G u e s san u m b e r :7 8 J u s tr i g h t

even.py
#A s k sf o ran u m b e r . #P r i n t si fi ti se v e no ro d d n u m b e r=i n p u t ( " T e l lm ean u m b e r :" ) i fn u m b e r%2= =0 : p r i n tn u m b e r ," i se v e n . " e l i fn u m b e r%2= =1 : p r i n tn u m b e r ," i so d d . " e l s e : p r i n tn u m b e r ," i sv e r ys t r a n g e . "

Sampleruns:
T e l lm ean u m b e r :3 3i so d d .

T e l lm ean u m b e r :2 2i se v e n .

T e l lm ean u m b e r :3 . 1 4 1 5 9 3 . 1 4 1 5 9i sv e r ys t r a n g e .

average1.py
#k e e p sa s k i n gf o rn u m b e r su n t i l0i se n t e r e d . #P r i n t st h ea v e r a g ev a l u e . c o u n t=0 s u m=0 . 0 n u m b e r=1#s e tt os o m e t h i n gt h a tw i l ln o te x i tt h ew h i l el o o pi m m e d i a t e l y .
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 26/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

p r i n t" E n t e r0t oe x i tt h el o o p " w h i l en u m b e r! =0 : n u m b e r=i n p u t ( " E n t e ran u m b e r :" ) i fn u m b e r! =0 : c o u n t=c o u n t+1 s u m=s u m+n u m b e r p r i n t" T h ea v e r a g ew a s : " ,s u m/c o u n t

Sampleruns:
E n t e r0t oe x i tt h el o o p E n t e ran u m b e r :3 E n t e ran u m b e r :5 E n t e ran u m b e r :0 T h ea v e r a g ew a s :4 . 0

E n t e r0t oe x i tt h el o o p E n t e ran u m b e r :1 E n t e ran u m b e r :4 E n t e ran u m b e r :3 E n t e ran u m b e r :0 T h ea v e r a g ew a s :2 . 6 6 6 6 6 6 6 6 6 6 7

average2.py
#k e e p sa s k i n gf o rn u m b e r su n t i lc o u n tn u m b e r sh a v eb e e ne n t e r e d . #P r i n t st h ea v e r a g ev a l u e . s u m=0 . 0 p r i n t" T h i sp r o g r a mw i l lt a k es e v e r a ln u m b e r st h e na v e r a g et h e m " c o u n t=i n p u t ( " H o wm a n yn u m b e r sw o u l dy o ul i k et oa v e r a g e :" ) c u r r e n t _ c o u n t=0 w h i l ec u r r e n t _ c o u n t<c o u n t : c u r r e n t _ c o u n t=c u r r e n t _ c o u n t+1 p r i n t" N u m b e r " ,c u r r e n t _ c o u n t n u m b e r=i n p u t ( " E n t e ran u m b e r :" ) s u m=s u m+n u m b e r p r i n t" T h ea v e r a g ew a s : " ,s u m/c o u n t

Sampleruns:
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 27/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

T h i sp r o g r a mw i l lt a k es e v e r a ln u m b e r st h e na v e r a g et h e m H o wm a n yn u m b e r sw o u l dy o ul i k et oa v e r a g e :2 N u m b e r1 E n t e ran u m b e r :3 N u m b e r2 E n t e ran u m b e r :5 T h ea v e r a g ew a s :4 . 0

T h i sp r o g r a mw i l lt a k es e v e r a ln u m b e r st h e na v e r a g et h e m H o wm a n yn u m b e r sw o u l dy o ul i k et oa v e r a g e :3 N u m b e r1 E n t e ran u m b e r :1 N u m b e r2 E n t e ran u m b e r :4 N u m b e r3 E n t e ran u m b e r :3 T h ea v e r a g ew a s :2 . 6 6 6 6 6 6 6 6 6 6 7

Exercises
Modifythehigherorlowerprogramfromthissectiontokeeptrackofhowmanytimestheuserhasenteredthewrongnumber.Ifitismorethan3times,print "Thatmusthavebeencomplicated."Notethattheprogramdoesnothavetoquitaskingforthenumberbeforeitisguessed,itjusthastoprintthisafterthe numberisguessed. Writeaprogramthatasksfortwonumbers.Ifthesumofthenumbersisgreaterthan100,print"Thatisabignumber." Writeaprogramthataskstheusertheirname,iftheyenteryournamesay"Thatisanicename",iftheyenter"JohnCleese"or"MichaelPalin",tellthemhow youfeelaboutthem),otherwisetellthem"Youhaveanicename." Solution Modifythehigherorlowerprogramfromthissectiontokeeptrackofhowmanytimestheuserhasenteredthewrongnumber.Ifitismorethan3times,print "Thatmusthavebeencomplicated."

n u m b e r=4 2 g u e s s=0 c o u n t=0 w h i l eg u e s s! =n u m b e r : c o u n t=c o u n t+1 g u e s s=i n p u t ( ' G u e s san u m b e r :' ) i fg u e s s>n u m b e r : p r i n t' T o oh i g h ' e l i fg u e s s<n u m b e r : p r i n t' T o ol o w '
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 28/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

e l s e : p r i n t' J u s tr i g h t ' b r e a k i fc o u n t>2 : p r i n t' T h a tm u s th a v eb e e nc o m p l i c a t e d . ' b r e a k

Writeaprogramthatasksfortwonumbers.Ifthesumofthenumbersisgreaterthan100,print"Thatisabignumber."

n u m b e r 1=i n p u t ( ' 1 s tn u m b e r :' ) n u m b e r 2=i n p u t ( ' 2 n dn u m b e r :' ) i fn u m b e r 1+n u m b e r 2>1 0 0 : p r i n t' T h a ti sab i gn u m b e r . '

Writeaprogramthataskstheusertheirname,iftheyenteryournamesay"Thatisanicename",iftheyenter"JohnCleese"or"MichaelPalin",tellthemhow youfeelaboutthem),otherwisetellthem"Youhaveanicename."

n a m e=r a w _ i n p u t ( ' Y o u rn a m e :' ) i fn a m e= =' A d a ' : p r i n t' T h a ti san i c en a m e . ' e l i fn a m e= =' J o h nC l e e s e 'o rn a m e= =' M i c h a e lP a l i n ' : p r i n t' . . .s o m ef u n n yt e x t . ' e l s e : p r i n t' Y o uh a v ean i c en a m e . '

Debugging
Whatisdebugging?
"Assoonaswestartedprogramming,wefoundtooursurprisethatitwasn'taseasytogetprogramsrightaswehadthought.Debugginghadtobe discovered.IcanremembertheexactinstantwhenIrealizedthatalargepartofmylifefromthenonwasgoingtobespentinfindingmistakesinmy ownprograms." MauriceWilkesdiscoversdebugging,1949 Bynowifyouhavebeenmessingaroundwiththeprogramsyouhaveprobablyfoundthatsometimestheprogramdoessomethingyoudidn'twantittodo. Thisisfairlycommon.Debuggingistheprocessoffiguringoutwhatthecomputerisdoingandthengettingittodowhatyouwantittodo.Thiscanbetricky.I oncespentnearlyaweektrackingdownandfixingabugthatwascausedbysomeoneputtingan x wherea y shouldhavebeen.
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 29/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

Thischapterwillbemoreabstractthanpreviouschapters.

Whatshouldtheprogramdo?
Thefirstthingtodo(thissoundsobvious)istofigureoutwhattheprogramshouldbedoingifitisrunningcorrectly.Comeupwithsometestcasesandsee whathappens.Forexample,let'ssayIhaveaprogramtocomputetheperimeterofarectangle(thesumofthelengthofalltheedges).Ihavethefollowing testcases: height width perimeter 3 2 4 2 5 4 3 4 2 1 14 10 16 8 12

InowrunmyprogramonallofthetestcasesandseeiftheprogramdoeswhatIexpectittodo.Ifitdoesn'tthenIneedtofindoutwhatthecomputeris doing. Morecommonlysomeofthetestcaseswillworkandsomewillnot.Ifthatisthecaseyoushouldtryandfigureoutwhattheworkingoneshaveincommon. Forexamplehereistheoutputforaperimeterprogram(yougettoseethecodeinaminute):


H e i g h t :3 W i d t h :4 p e r i m e t e r=1 5

H e i g h t :2 W i d t h :3 p e r i m e t e r=1 1

H e i g h t :4 W i d t h :4 p e r i m e t e r=1 6

H e i g h t :2 W i d t h :2 p e r i m e t e r=8

en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version

30/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

H e i g h t :5 W i d t h :1 p e r i m e t e r=8

Noticethatitdidn'tworkforthefirsttwoinputs,itworkedforthenexttwoanditdidn'tworkonthelastone.Tryandfigureoutwhatisincommonwiththe workingones.Onceyouhavesomeideawhattheproblemisfindingthecauseiseasier.Withyourownprogramsyoushouldtrymoretestcasesifyouneed them.

Whatdoestheprogramdo?
Thenextthingtodoistolookatthesourcecode.Oneofthemostimportantthingstodowhileprogrammingisreadingsourcecode.Theprimarywaytodo thisiscodewalkthroughs. Acodewalkthroughstartsatthefirstline,andworksitswaydownuntiltheprogramisdone. W h i l e loopsand i f statementsmeanthatsomelinesmayneverbe runandsomelinesarerunmanytimes.AteachlineyoufigureoutwhatPythonhasdone. Letsstartwiththesimpleperimeterprogram.Don'ttypeitin,youaregoingtoreadit,notrunit.Thesourcecodeis:
h e i g h t=i n p u t ( " H e i g h t :" ) w i d t h=i n p u t ( " W i d t h :" ) p r i n t" p e r i m e t e r= " ,w i d t h+h e i g h t+w i d t h+w i d t h

Question: WhatisthefirstlinePythonruns? Answer: Thefirstlineisalwaysrunfirst.Inthiscaseitis: h e i g h t=i n p u t ( " H e i g h t :" ) Whatdoesthatlinedo? Prints H e i g h t : ,waitsfortheusertotypeanumberin,andputsthatinthevariableheight. Whatisthenextlinethatruns? Ingeneral,itisthenextlinedownwhichis: w i d t h=i n p u t ( " W i d t h :" ) Whatdoesthatlinedo? Prints W i d t h : ,waitsfortheusertotypeanumberin,andputswhattheusertypesinthevariablewidth. Whatisthenextlinethatruns? Whenthenextlineisnotindentedmoreorlessthanthecurrentline,itisthelinerightafterwards,soitis: p r i n t" p e r i m e t e r=" ,w i d t h+h e i g h t+w i d t h+
w i d t h (Itmayalsorunafunctioninthecurrentline,butthat'safuturechapter.)Whatdoesthatlinedo?

Firstitprints p e r i m e t e r= ,thenitprints w i d t h+h e i g h t+w i d t h+w i d t h . Does w i d t h+h e i g h t+w i d t h+w i d t h calculatetheperimeterproperly? Let'ssee,perimeterofarectangleisthebottom(width)plustheleftside(height)plusthetop(width)plustherightside(huh?).Thelastitemshouldbe therightside'slength,ortheheight. Doyouunderstandwhysomeofthetimestheperimeterwascalculated"correctly"?
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 31/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

Itwascalculatedcorrectlywhenthewidthandtheheightwereequal. Thenextprogramwewilldoacodewalkthroughforisaprogramthatissupposedtoprintout5dotsonthescreen.However,thisiswhattheprogramis outputting:


....

Andhereistheprogram:
n u m b e r=5 w h i l en u m b e r>1 : p r i n t" . " , n u m b e r=n u m b e r-1 p r i n t

Thisprogramwillbemorecomplextowalkthroughsinceitnowhasindentedportions(orcontrolstructures).Letusbegin. Whatisthefirstlinetoberun? Thefirstlineofthefile: n u m b e r=5 Whatdoesitdo? Putsthenumber5inthevariablenumber. Whatisthenextline? Thenextlineis: w h i l en u m b e r>1 : Whatdoesitdo? Well, w h i l e statementsingenerallookattheirexpression,andifitistruetheydothenextindentedblockofcode,otherwisetheyskipthenextindented blockofcode. Sowhatdoesitdorightnow? If n u m b e r>1 istruethenthenexttwolineswillberun. Sois n u m b e r>1 ? Thelastvalueputinto n u m b e r was 5 and 5>1 soyes. Sowhatisthenextline? Sincethe w h i l e wastruethenextlineis: p r i n t" . " , Whatdoesthatlinedo? Printsonedotandsincethestatementendswitha','thenextprintstatementwillnotbeonadifferentscreenline. Whatisthenextline? n u m b e r=n u m b e r-1 sincethatisfollowinglineandtherearenoindentchanges. Whatdoesitdo?
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 32/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

Itcalculates n u m b e r-1 ,whichisthecurrentvalueof n u m b e r (or5)subtracts1fromit,andmakesthatthenewvalueofnumber.Sobasicallyitchanges


n u m b e r 'svaluefrom5to4.

Whatisthenextline? Well,theindentleveldecreasessowehavetolookatwhattypeofcontrolstructureitis.Itisa w h i l e loop,sowehavetogobacktothe w h i l e clause whichis w h i l en u m b e r>1 : Whatdoesitdo? Itlooksatthevalueofnumber,whichis4,andcomparesitto1andsince 4>1 thewhileloopcontinues. Whatisthenextline? Sincethewhileloopwastrue,thenextlineis: p r i n t" . " , Whatdoesitdo? Itprintsaseconddotontheline. Whatisthenextline? Noindentchangesoitis: n u m b e r=n u m b e r-1 Andwhatdoesitdo? Ittakesthecurrentvalueofnumber(4),subtracts1fromit,whichgivesit3andthenfinallymakes3thenewvalueofnumber. Whatisthenextline? Sincethereisanindentchangecausedbytheendofthewhileloop,thenextlineis: w h i l en u m b e r>1 : Whatdoesitdo? Itcomparesthecurrentvalueofnumber(3)to1. 3>1 sothewhileloopcontinues. Whatisthenextline? Sincethewhileloopconditionwastruethenextlineis: p r i n t" . " , Anditdoeswhat? Athirddotisprintedontheline. Whatisthenextline? Itis: n u m b e r=n u m b e r-1 Whatdoesitdo? Ittakesthecurrentvalueofnumber(3)subtractsfromit1andmakesthe2thenewvalueofnumber. Whatisthenextline? Backuptothestartofthewhileloop: w h i l en u m b e r>1 : Whatdoesitdo? Itcomparesthecurrentvalueofnumber(2)to1.Since 2>1 thewhileloopcontinues. Whatisthenextline? Sincethewhileloopiscontinuing: p r i n t" . " , Whatdoesitdo? Itdiscoversthemeaningoflife,theuniverseandeverything.I'mjoking.(Ihadtomakesureyouwereawake.)Thelineprintsafourthdotonthescreen.
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 33/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

Whatisthenextline? It's: n u m b e r=n u m b e r-1 Whatdoesitdo? Takesthecurrentvalueofnumber(2)subtracts1andmakes1thenewvalueofnumber. Whatisthenextline? Backuptothewhileloop: w h i l en u m b e r>1 : Whatdoesthelinedo? Itcomparesthecurrentvalueofnumber(1)to1.Since 1>1 isfalse(oneisnotgreaterthanone),thewhileloopexits. Whatisthenextline? Sincethewhileloopconditionwasfalsethenextlineisthelineafterthewhileloopexits,or: p r i n t Whatdoesthatlinedo? Makesthescreengotothenextline. Whydoesn'ttheprogramprint5dots? Theloopexits1dottoosoon. Howcanwefixthat? Maketheloopexit1dotlater. Andhowdowedothat? Thereareseveralways.Onewaywouldbetochangethewhileloopto: w h i l en u m b e r>0 : Anotherwaywouldbetochangetheconditionalto: n u m b e r> =1 Thereareacoupleothers.

HowdoIfixtheprogram?
Youneedtofigureoutwhattheprogramisdoing.Youneedtofigureoutwhattheprogramshoulddo.Figureoutwhatthedifferencebetweenthetwois. Debuggingisaskillthathastobepracticedtobelearned.Ifyoucan'tfigureitoutafteranhour,takeabreak,talktosomeoneabouttheproblemor contemplatethelintinyournavel,jumpoffabridge.Comebackinawhileandyouwillprobablyhavenewideasabouttheproblem.Goodluck.

DefiningFunctions
CreatingFunctions
TostartoffthischapterIamgoingtogiveyouanexampleofwhatyoucoulddobutshouldn't(sodon'ttypeitin):
a=2 3 b=2 3 i fa<0 : a=a
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 34/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

i fb<0 : b=b i fa= =b : p r i n t" T h ea b s o l u t ev a l u e so f " ,a ," a n d " ,b ," a r ee q u a l " e l s e : p r i n t" T h ea b s o l u t ev a l u e so f " ,a ," a n d " ,b ," a r ed i f f e r e n t "

withtheoutputbeing:
T h ea b s o l u t ev a l u e so f2 3a n d2 3a r ee q u a l

Theprogramseemsalittlerepetitive.Programmershatetorepeatthingsthat'swhatcomputersarefor,afterall!(Notealsothatfindingtheabsolutevalue changedthevalueofthevariable,whichiswhyitisprintingout23,andnot23intheoutput.)FortunatelyPythonallowsyoutocreatefunctionstoremove duplication.Hereistherewrittenexample:


d e fa b s o l u t e _ v a l u e ( n ) : i fn<0 : n=n r e t u r nn a=2 3 b=2 3 i fa b s o l u t e _ v a l u e ( a )= =a b s o l u t e _ v a l u e ( b ) : p r i n t" T h ea b s o l u t ev a l u e so f " ,a ," a n d " ,b ," a r ee q u a l " e l s e : p r i n t" T h ea b s o l u t ev a l u e so f " ,a ," a n d " ,b ," a r ed i f f e r e n t "

withtheoutputbeing:
T h ea b s o l u t ev a l u e so f2 3a n d2 3a r ee q u a l

Thekeyfeatureofthisprogramisthe d e f statement. d e f (shortfordefine)startsafunctiondefinition. d e f isfollowedbythenameofthefunction a b s o l u t e _ v a l u e . Nextcomesa'('followedbytheparameter n (n ispassedfromtheprogramintothefunctionwhenthefunctioniscalled).Thestatementsafterthe':'are executedwhenthefunctionisused.Thestatementscontinueuntileithertheindentedstatementsendora r e t u r n isencountered.The r e t u r n statementreturns avaluebacktotheplacewherethefunctionwascalled. Noticehowthevaluesof a and b arenotchanged.Functionscanbeusedtorepeattasksthatdon'treturnvalues.Herearesomeexamples:
d e fh e l l o ( ) : p r i n t" H e l l o " d e fa r e a ( w ,h ) : r e t u r nw*h
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 35/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

d e fp r i n t _ w e l c o m e ( n a m e ) : p r i n t" W e l c o m e " ,n a m e h e l l o ( ) h e l l o ( ) p r i n t _ w e l c o m e ( " F r e d " ) w=4 h=5 p r i n t" w i d t h= " ,w ," h e i g h t= " ,h ," a r e a= " ,a r e a ( w ,h )

withoutputbeing:
H e l l o H e l l o W e l c o m eF r e d w i d t h=4h e i g h t=5a r e a=2 0

Thatexampleshowssomemorestuffthatyoucandowithfunctions.Noticethatyoucanusenoargumentsortwoormore.Noticealsowhenafunction doesn'tneedtosendbackavalue,areturnisoptional.

Variablesinfunctions
Wheneliminatingrepeatedcode,youoftenhavevariablesintherepeatedcode.InPython,thesearedealtwithinaspecialway.Sofarallvariableswehave seenareglobalvariables.Functionshaveaspecialtypeofvariablecalledlocalvariables.Thesevariablesonlyexistwhilethefunctionisrunning.Whenalocal variablehasthesamenameasanothervariable(suchasaglobalvariable),thelocalvariablehidestheother.Soundconfusing?Well,thesenextexamples (whichareabitcontrived)shouldhelpclearthingsup.
a=4 d e fp r i n t _ f u n c ( ) : a=1 7 p r i n t" i n p r i n t _ f u n ca=" ,a p r i n t _ f u n c ( ) p r i n t" a=" ,a

Whenrun,wewillreceiveanoutputof:
i np r i n t _ f u n ca=1 7 a=4

en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version

Variableassignmentsinsideafunctiondonotoverrideglobalvariables,theyexistonlyinsidethefunction.Eventhough a wasassignedanewvalueinsidethe 36/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

Variableassignmentsinsideafunctiondonotoverrideglobalvariables,theyexistonlyinsidethefunction.Eventhough a wasassignedanewvalueinsidethe function,thisnewlyassignedvaluewasonlyrelevantto p r i n t _ f u n c ,whenthefunctionfinishesrunning,andthe a 'svaluesisprintedagain,weseetheoriginally assignedvalues.

Complexexample
a _ v a r=1 0 b _ v a r=1 5 e _ v a r=2 5 d e fa _ f u n c ( a _ v a r ) : p r i n t" i na _ f u n ca _ v a r=" ,a _ v a r b _ v a r=1 0 0+a _ v a r d _ v a r=2*a _ v a r p r i n t" i na _ f u n cb _ v a r=" ,b _ v a r p r i n t" i na _ f u n cd _ v a r=" ,d _ v a r p r i n t" i na _ f u n ce _ v a r=" ,e _ v a r r e t u r nb _ v a r+1 0 c _ v a r=a _ f u n c ( b _ v a r ) p r i n t" a _ v a r=" ,a _ v a r p r i n t" b _ v a r=" ,b _ v a r p r i n t" c _ v a r=" ,c _ v a r p r i n t" d _ v a r=" ,d _ v a r

Theoutputis:
i na _ f u n ca _ v a r= i na _ f u n cb _ v a r= i na _ f u n cd _ v a r= i na _ f u n ce _ v a r= a _ v a r= 1 0 b _ v a r= 1 5 c _ v a r= 1 2 5 d _ v a r= 1 5 1 1 5 3 0 2 5

T r a c e b a c k( m o s tr e c e n tc a l ll a s t ) : F i l e" C : \ P y t h o n 2 4 \ d e f 2 " ,l i n e1 9 ,i nt o p l e v e l p r i n t" d _ v a r=" ,d _ v a r N a m e E r r o r :n a m e' d _ v a r 'i sn o td e f i n e d

Inthisexamplethevariables a _ v a r , b _ v a r ,and d _ v a r arealllocalvariableswhentheyareinsidethefunction a _ f u n c .Afterthestatement r e t u r nb _ v a r+1 0 isrun, theyallceasetoexist.Thevariable a _ v a r isautomaticallyalocalvariablesinceitisaparametername.Thevariables b _ v a r and d _ v a r arelocalvariablessince theyappearontheleftofanequalssigninthefunctioninthestatements b _ v a r=1 0 0+a _ v a r and d _ v a r=2*a _ v a r . Insideofthefunction a _ v a r hasnovalueassignedtoit.Whenthefunctioniscalledwith c _ v a r=a _ f u n c ( b _ v a r ) ,15isassignedto a _ v a r sinceatthatpointintime 37/99 en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

Insideofthefunction a _ v a r hasnovalueassignedtoit.Whenthefunctioniscalledwith c _ v a r=a _ f u n c ( b _ v a r ) ,15isassignedto a _ v a r sinceatthatpointintime b _ v a r is15,makingthecalltothefunction a _ f u n c ( 1 5 ) .Thisendsupsetting a _ v a r to15whenitisinsideof a _ f u n c . Asyoucansee,oncethefunctionfinishesrunning,thelocalvariables a _ v a r and b _ v a r thathadhiddentheglobalvariablesofthesamenamearegone.Then thestatement p r i n t" a _ v a r=" ,a _ v a r printsthevalue 1 0 ratherthanthevalue 1 5 sincethelocalvariablethathidtheglobalvariableisgone. Anotherthingtonoticeisthe N a m e E r r o r thathappensattheend.Thisappearssincethevariable d _ v a r nolongerexistssince a _ f u n c finished.Allthelocal variablesaredeletedwhenthefunctionexits.Ifyouwanttogetsomethingfromafunction,thenyouwillhavetouse r e t u r ns o m e t h i n g . Onelastthingtonoticeisthatthevalueof e _ v a r remainsunchangedinside a _ f u n c sinceitisnotaparameteranditneverappearsontheleftofanequalssign insideofthefunction a _ f u n c .Whenaglobalvariableisaccessedinsideafunctionitistheglobalvariablefromtheoutside. Functionsallowlocalvariablesthatexistonlyinsidethefunctionandcanhideothervariablesthatareoutsidethefunction.

Examples
temperature2.py
#c o n v e r t st e m p e r a t u r et of a h r e n h e i to rc e l s i u s d e fp r i n t _ o p t i o n s ( ) : p r i n t" O p t i o n s : " p r i n t"' p 'p r i n to p t i o n s " p r i n t"' c 'c o n v e r tf r o mc e l s i u s " p r i n t"' f 'c o n v e r tf r o mf a h r e n h e i t " p r i n t"' q 'q u i tt h ep r o g r a m " d e fc e l s i u s _ t o _ f a h r e n h e i t ( c _ t e m p ) : r e t u r n9 . 0/5 . 0*c _ t e m p+3 2 d e ff a h r e n h e i t _ t o _ c e l s i u s ( f _ t e m p ) : r e t u r n( f _ t e m p-3 2 . 0 )*5 . 0/9 . 0 c h o i c e=" p " w h i l ec h o i c e! =" q " : i fc h o i c e= =" c " : t e m p=i n p u t ( " C e l s i u st e m p e r a t u r e :" ) p r i n t" F a h r e n h e i t : " ,c e l s i u s _ t o _ f a h r e n h e i t ( t e m p ) e l i fc h o i c e= =" f " : t e m p=i n p u t ( " F a h r e n h e i tt e m p e r a t u r e :" ) p r i n t" C e l s i u s : " ,f a h r e n h e i t _ t o _ c e l s i u s ( t e m p ) e l i fc h o i c e! =" q " : p r i n t _ o p t i o n s ( ) c h o i c e=r a w _ i n p u t ( " o p t i o n :" )

SampleRun:
O p t i o n s :
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 38/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

' p 'p r i n to p t i o n s ' c 'c o n v e r tf r o mc e l s i u s ' f 'c o n v e r tf r o mf a h r e n h e i t ' q 'q u i tt h ep r o g r a m o p t i o n :c C e l s i u st e m p e r a t u r e :3 0 F a h r e n h e i t :8 6 . 0 o p t i o n :f F a h r e n h e i tt e m p e r a t u r e :6 0 C e l s i u s :1 5 . 5 5 5 5 5 5 5 5 5 6 o p t i o n :q

area2.py
#B yA m o sS a t t e r l e e p r i n t d e fh e l l o ( ) : p r i n t' H e l l o ! ' d e fa r e a ( w i d t h ,h e i g h t ) : r e t u r nw i d t h*h e i g h t d e fp r i n t _ w e l c o m e ( n a m e ) : p r i n t' W e l c o m e , ' ,n a m e n a m e=r a w _ i n p u t ( ' Y o u rN a m e :' ) h e l l o ( ) , p r i n t _ w e l c o m e ( n a m e ) p r i n t p r i n t' T of i n dt h ea r e ao far e c t a n g l e , ' p r i n t' e n t e rt h ew i d t ha n dh e i g h tb e l o w . ' p r i n t w=i n p u t ( ' W i d t h :' ) w h i l ew< =0 : p r i n t' M u s tb eap o s i t i v en u m b e r ' w=i n p u t ( ' W i d t h :' ) h=i n p u t ( ' H e i g h t :' ) w h i l eh< =0 : p r i n t' M u s tb eap o s i t i v en u m b e r ' h=i n p u t ( ' H e i g h t :' ) p r i n t' W i d t h= ' ,w ,' H e i g h t= ' ,h ,' s oA r e a= ' ,a r e a ( w ,h )

SampleRun:
Y o u rN a m e :J o s h H e l l o ! W e l c o m e ,J o s h
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 39/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

T of i n dt h ea r e ao far e c t a n g l e , e n t e rt h ew i d t ha n dh e i g h tb e l o w . W i d t h :4 M u s tb eap o s i t i v en u m b e r W i d t h :4 H e i g h t :3 W i d t h=4H e i g h t=3s oA r e a=1 2

Exercises
Rewritethearea2.pyprogramfromtheExamplesabovetohaveaseparatefunctionfortheareaofasquare,theareaofarectangle,andtheareaofacircle (3 . 1 4*r a d i u s* *2 ).Thisprogramshouldincludeamenuinterface. Solution Rewritethearea2.pyprogramfromtheExamplesabovetohaveaseparatefunctionfortheareaofasquare,theareaofarectangle,andtheareaofacircle (3 . 1 4*r a d i u s* *2 ).Thisprogramshouldincludeamenuinterface.

d e fs q u a r e ( l e n g t h ) : r e t u r nl e n g t h*l e n g t h d e fr e c t a n g l e ( w i d t h,h e i g h t ) : r e t u r nw i d t h*h e i g h t d e fc i r c l e ( r a d i u s ) : r e t u r n3 . 1 4*r a d i u s* *2 d e fo p t i o n s ( ) : p r i n t p r i n t" O p t i o n s : " p r i n t" s=c a l c u l a t et h ea r e ao fas q u a r e . " p r i n t" c=c a l c u l a t et h ea r e ao fac i r c l e . " p r i n t" r=c a l c u l a t et h ea r e ao far e c t a n g l e . " p r i n t" q=q u i t " p r i n t p r i n t" T h i sp r o g r a mw i l lc a l c u l a t et h ea r e ao fas q u a r e ,c i r c l eo rr e c t a n g l e . " c h o i c e=" x " o p t i o n s ( ) w h i l ec h o i c e! =" q " : c h o i c e=r a w _ i n p u t ( " P l e a s ee n t e ry o u rc h o i c e :" ) i fc h o i c e= =" s " : l e n g t h=i n p u t ( " L e n g t ho fs q u a r e :" ) p r i n t" T h ea r e ao ft h i ss q u a r ei s " ,s q u a r e ( l e n g t h ) o p t i o n s ( ) e l i fc h o i c e= =" c " : r a d i u s=i n p u t ( " R a d i u so ft h ec i r c l e :" )
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 40/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

p r i n t" T h ea r e ao ft h ec i r c l ei s " ,c i r c l e ( r a d i u s ) o p t i o n s ( ) e l i fc h o i c e= =" r " : w i d t h=i n p u t ( " W i d t ho ft h er e c t a n g l e :" ) h e i g h t=i n p u t ( " H e i g h to ft h er e c t a n g l e :" ) p r i n t" T h ea r e ao ft h er e c t a n g l ei s " ,r e c t a n g l e ( w i d t h ,h e i g h t ) o p t i o n s ( ) e l i fc h o i c e= =" q " : p r i n t" " , e l s e : p r i n t" U n r e c o g n i z e do p t i o n . " o p t i o n s ( )

AdvancedFunctionsExample
Somepeoplefindthissectionuseful,andsomefinditconfusing.Ifyoufinditconfusingyoucanskipit(orjustlookattheexamples.)Nowwewilldoawalk throughforthefollowingprogram:
d e fm u l t ( a ,b ) : i fb= =0 : r e t u r n0 r e s t=m u l t ( a ,b-1 ) v a l u e=a+r e s t r e t u r nv a l u e p r i n t" 3*2=" ,m u l t ( 3 ,2 )

Output

3*2= 6

Basicallythisprogramcreatesapositiveintegermultiplicationfunction(thatisfarslowerthanthebuiltinmultiplicationfunction)andthendemonstratesthis functionwithauseofthefunction.Thisprogramdemonstratestheuseofrecursion,thatisaformofiteration(repetition)inwhichthereisafunctionthat repeatedlycallsitselfuntilanexitconditionissatisfied.Itusesrepeatedadditionstogivethesameresultasmutiplication:e.g.3+3(addition)givesthesame resultas3*2(multiplication). RUN1 Question: Whatisthefirstthingtheprogramdoes? Answer: Thefirstthingdoneisthefunctionmultisdefinedwithallthelinesexceptthelastone.

en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version

41/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

functionmultdefined

d e fm u l t ( a ,b ) : i fb= =0 : r e t u r n0 r e s t=m u l t ( a ,b-1 ) v a l u e=a+r e s t r e t u r nv a l u e

Thiscreatesafunctionthattakestwoparametersandreturnsavaluewhenitisdone.Laterthisfunctioncanberun.

Whathappensnext? Thenextlineafterthefunction, p r i n t" 3*2=" ,m u l t ( 3 ,2 ) isrun.

Andwhatdoesthisdo? Itprints 3*2= andthereturnvalueof m u l t ( 3 ,2 )

Andwhatdoes m u l t ( 3 ,2 ) return? Weneedtodoawalkthroughofthe m u l t functiontofindout. RUN2 Whathappensnext? Thevariable a getsthevalue3assignedtoitandthevariable b getsthevalue2assignedtoit.

Andthen? Theline i fb= =0 : isrun.Since b hasthevalue2thisisfalsesotheline r e t u r n0 isskipped.

Andwhatthen? Theline r e s t=m u l t ( a ,b-1 ) isrun.Thislinesetsthelocalvariable r e s t tothevalueof m u l t ( a ,b-1 ) .Thevalueof a is3andthevalueof b is2sothe functioncallis m u l t ( 3 , 1 )

Sowhatisthevalueof m u l t ( 3 ,1 ) ?
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 42/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

Wewillneedtorunthefunction m u l t withtheparameters3and1. RUN2

d e fm u l t ( 3 ,2 ) : i fb= =0 : r e t u r n0 r e s t=m u l t ( 3 ,2-1 ) r e s t=m u l t ( 3 ,1 ) v a l u e=3+r e s t r e t u r nv a l u e

RUN3 Sowhathappensnext? Thelocalvariablesinthe newrunofthefunctionaresetsothat a hasthevalue3and b hasthevalue1.Sincethesearelocalvaluesthesedonot affectthepreviousvaluesof a and b .

Andthen? Since b hasthevalue1theifstatementisfalse,sothenextlinebecomes r e s t=m u l t ( a ,b-1 ) .

Whatdoesthislinedo? Thislinewillassignthevalueof m u l t ( 3 ,0 ) torest.

Sowhatisthatvalue? Wewillhavetorunthefunctiononemoretimetofindthatout.Thistime a hasthevalue3and b hasthevalue0.

Sowhathappensnext? Thefirstlineinthefunctiontorunis i fb= =0 : . b hasthevalue0sothenextlinetorunis r e t u r n0

Andwhatdoestheline r e t u r n0 do? Thislinereturnsthevalue0outofthefunction.


en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 43/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

So? Sonowweknowthat m u l t ( 3 ,0 ) hasthevalue0.Nowweknowwhattheline r e s t=m u l t ( a ,b-1 ) didsincewehaverunthefunction m u l t withthe parameters3and0.Wehavefinishedrunning m u l t ( 3 ,0 ) andarenowbacktorunning m u l t ( 3 ,1 ) .Thevariable r e s t getsassignedthevalue0.

Whatlineisrunnext? Theline v a l u e=a+r e s t isrunnext.Inthisrunofthefunction, a=3 and r e s t=0 sonow v a l u e=3 .

Whathappensnext? Theline r e t u r nv a l u e isrun.Thisreturns3fromthefunction.Thisalsoexitsfromtherunofthefunction m u l t ( 3 ,1 ) .After r e t u r n iscalled,wegobackto running m u l t ( 3 ,2 ) .

Wherewerewein m u l t ( 3 ,2 ) ? Wehadthevariables a=3 and b=2 andwereexaminingtheline r e s t=m u l t ( a ,b-1 ) .

Sowhathappensnow? Thevariable r e s t get3assignedtoit.Thenextline v a l u e=a+r e s t sets v a l u e to 3+3 or6.

Sonowwhathappens? Thenextlineruns,thisreturns6fromthefunction.Wearenowbacktorunningtheline p r i n t" 3*2=" ,m u l t ( 3 ,2 ) whichcannowprintoutthe6.

Whatishappeningoverall? Basicallyweusedtwofactstocalculatethemultipleofthetwonumbers.Thefirstisthatanynumbertimes0is0(x*0=0 ).Thesecondisthata numbertimesanothernumberisequaltothefirstnumberplusthefirstnumbertimesonelessthanthesecondnumber(x*y=x+x*( y-1 ) ).Sowhat happensis 3*2 isfirstconvertedinto 3+3*1 .Then 3*1 isconvertedinto 3+3*0 .Thenweknowthatanynumbertimes0is0so 3*0 is0.Thenwe cancalculatethat 3+3*0 is 3+0 whichis 3 .Nowweknowwhat 3*1 issowecancalculatethat 3+3*1 is 3+3 whichis 6 . Thisishowthewholethingworks:
3*2 3+3*1 3+3+3*0 3+3+0
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 44/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

3+3 6

Shouldyoustillhaveproblemswiththisexample,lookattheprocessbackwards.Whatisthelaststepthathappens?Wecaneasilymakeoutthattheresultof m u l t ( 3 ,0 ) is 0 .Since b is 0 ,thefunction m u l t ( 3 ,0 ) willreturn 0 andstop. Sowhatdoesthepreviousstepdo? m u l t ( 3 ,1 ) doesnotreturn 0 because b isnot 0 .Sothenextlinesareexecuted: r e s t=m u l t( a ,b-1 ) ,whichis r e s t=m u l t( 3 , 0 ) ,whichis 0 aswejustworkedout.Sonowthevariable r e s t issetto 0 . Thenextlineaddsthevalueof r e s t to a ,andsince a is 3 and r e s t is 0 ,theresultis 3 . Nowweknowthatthefunction m u l t ( 3 ,1 ) returns 3 .Butwewanttoknowtheresultof m u l t ( 3 , 2 ) .Therefore,weneedtojumpbacktothestartoftheprogram andexecuteitonemoreround: m u l t ( 3 ,2 ) sets r e s t totheresultof m u l t ( 3 ,1 ) .Weknowfromthelastroundthatthisresultis 3 .Then v a l u e calculatesas a+r e s t , i.e. 3+3 .Thentheresultof3*2isprintedas6. Thepointofthisexampleisthatthefunction m u l t ( a ,b ) startsitselfinsideitself.Itdoesthisuntil b reaches 0 andthencalculatestheresultasexplainedabove. Recursion Programmingconstructsofthiskindarecalled recursiveandprobablythemostintuitivedefinitionof recursionis: Recursion Ifyoustilldon'tgetit,see recursion. Theselasttwosectionswererecentlywritten.Ifyouhaveanycomments,foundanyerrorsorthinkIneedmore/clearerexplanationspleaseemail.Ihavebeen knowninthepasttomakesimplethingsincomprehensible.Iftherestofthetutorialhasmadesense,butthissectiondidn't,itisprobablymyfaultandIwould liketoknow.Thanks.

Examples
factorial.py
# d e f i n e saf u n c t i o nt h a tc a l c u l a t e st h ef a c t o r i a l d e ff a c t o r i a l ( n ) : i fn< =1 : r e t u r n1 r e t u r nn*f a c t o r i a l ( n-1 ) p r i n t" 2 != " ,f a c t o r i a l ( 2 ) p r i n t" 3 != " ,f a c t o r i a l ( 3 ) p r i n t" 4 != " ,f a c t o r i a l ( 4 ) p r i n t" 5 != " ,f a c t o r i a l ( 5 )
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 45/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

Output:
2 !=2 3 !=6 4 !=2 4 5 !=1 2 0

countdown.py
d e fc o u n t _ d o w n ( n ) : p r i n tn i fn>0 : r e t u r nc o u n t _ d o w n ( n 1 ) c o u n t _ d o w n ( 5 )

Output:
5 4 3 2 1 0

Commentedfunction_interesting.py
#T h ec o m m e n t sb e l o wh a v eb e e nn u m b e r e da ss t e p s ,t om a k ee x p l a n a t i o n #o ft h ec o d ee a s i e r .P l e a s er e a da c c o r d i n gt ot h o s es t e p s . #( s t e pn u m b e r1 ,f o re x a m p l e ,i sa tt h eb o t t o m ) d e fm u l t ( a ,b ) :#( 2 . )T h i sf u n c t i o nw i l lk e e pr e p e a t i n gi t s e l f ,b e c a u s e . . . . i fb= =0 : r e t u r n0 r e s t=m u l t ( a ,b-1 )#( 3 . ). . . . O n c ei tr e a c h e sT H I S ,t h es e q u e n c es t a r t so v e ra g a i na n dg o e sb a c kt ot h et o p ! v a l u e=a+r e s t r e t u r nv a l u e#( 4 . )t h e r e f o r e ," r e t u r nv a l u e "w i l ln o th a p p e nu n t i lt h ep r o g r a mg e t sp a s ts t e p3a b o v e p r i n t" 3*2=" ,m u l t ( 3 ,2 )#( 1 . )T h e" m u l t "f u n c t i o nw i l lf i r s ti n i t i a t eh e r e #T h e" r e t u r nv a l u e "e v e n ta tt h ee n dc a nt h e r e f o r eo n l yh a p p e n #o n c ebe q u a l sz e r o( bd e c r e a s e sb y1e v e r y t i m es t e p3h a p p e n s ) . #A n do n l yt h e nc a nt h ep r i n tc o m m a n da tt h eb o t t o mb ed i s p l a y e d .

en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version

46/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

#S e ei ta sk i n do fa" j u m p a r o u n d "e f f e c t .B a s i c a l l y ,a l ly o u #s h o u l dr e a l l yu n d e r s t a n di st h a tt h ef u n c t i o ni sr e i n i t i a t e d #W I T H I NI T S E L Fa ts t e p3 .T h e r e f o r e ,t h es e q u e n c e" j u m p s "b a c k #t ot h et o p .

Commentedfactorial.py
#A n o t h e r" j u m p a r o u n d "f u n c t i o ne x a m p l e : d e ff a c t o r i a l ( n ) :#( 2 . )S oo n c ea g a i n ,t h i sf u n c t i o nw i l lR E P E A Ti t s e l f . . . . i fn< =1 : r e t u r n1 r e t u r nn*f a c t o r i a l ( n-1 )#( 3 . )B e c a u s ei tR E i n i t i a t e sH E R E ,a n dg o e sb a c kt ot h et o p . p r i n t" 2 != " ,f a c t o r i a l ( 2 )#( 1 . )T h e" f a c t o r i a l "f u n c t i o ni si n i t i a t e dw i t ht h i sl i n e p r i n t" 3 != " ,f a c t o r i a l ( 3 ) p r i n t" 4 != " ,f a c t o r i a l ( 4 ) p r i n t" 5 != " ,f a c t o r i a l ( 5 )

Commentedcountdown.py
#A n o t h e r" j u m p a r o u n d " ,n i c ea n de a s y : d e fc o u n t _ d o w n ( n ) :#( 2 . )O n c ea g a i n ,t h i ss e q u e n c ew i l lr e p e a ti t s e l f . . . . p r i n tn i fn>0 : r e t u r nc o u n t _ d o w n ( n 1 )#( 3 . )B e c a u s ei tr e s t a r t sh e r e ,a n dg o e sb a c kt ot h et o p c o u n t _ d o w n ( 5 )#( 1 . )T h e" c o u n t _ d o w n "f u n c t i o ni n i t i a t e sh e r e

Lists
Variableswithmorethanonevalue
Youhavealreadyseenordinaryvariablesthatstoreasinglevalue.Howeverothervariabletypescanholdmorethanonevalue.Thesimplesttypeiscalleda list.Hereisanexampleofalistbeingused:
w h i c h _ o n e=i n p u t ( " W h a tm o n t h( 1 1 2 ) ?" ) m o n t h s=[ ' J a n u a r y ' ,' F e b r u a r y ' ,' M a r c h ' ,' A p r i l ' ,' M a y ' ,' J u n e ' ,' J u l y ' , ' A u g u s t ' ,' S e p t e m b e r ' ,' O c t o b e r ' ,' N o v e m b e r ' ,' D e c e m b e r ' ] i f1< =w h i c h _ o n e< =1 2 : p r i n t" T h em o n t hi s " ,m o n t h s [ w h i c h _ o n e-1 ]
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 47/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

andanoutputexample:
W h a tm o n t h( 1 1 2 ) ?3 T h em o n t hi sM a r c h

Inthisexamplethe m o n t h s isalist. m o n t h s isdefinedwiththelines m o n t h s=[ ' J a n u a r y ' ,' F e b r u a r y ' ,' M a r c h ' ,' A p r i l ' ,' M a y ' ,' J u n e ' ,' J u l y ' , and ' A u g u s t ' ,' S e p t e m b e r ' , ' O c t o b e r ' ,' N o v e m b e r ' ,' D e c e m b e r ' ] (notethata \ couldalsobeusedtosplitalongline,butthatisnotnecessaryinthiscasebecausePythonisintelligentenough torecognizethateverythingwithinbracketsbelongstogether).The [ and ] startandendthelistwithcommas(, )separatingthelistitems.Thelistisusedin m o n t h s [ w h i c h _ o n e-1 ] .Alistconsistsofitemsthatarenumberedstartingat0.InotherwordsifyouwantedJanuaryyouwoulduse m o n t h s [ 0 ] .Givealistanumber anditwillreturnthevaluethatisstoredatthatlocation. Thestatement i f1< =w h i c h _ o n e< =1 2 : willonlybetrueif w h i c h _ o n e isbetweenoneandtwelveinclusive(inotherwordsitiswhatyouwouldexpectifyouhave seenthatinalgebra). Listscanbethoughtofasaseriesofboxes.Eachboxhasadifferentvalue.Forexample,theboxescreatedby d e m o l i s t=[ ' l i f e ' ,4 2 ,' t h eu n i v e r s e ' ,6 ,' a n d ' ,7 ] wouldlooklikethis: boxnumber demolist 0 1 2 3 4 5

"life" 42 "theuniverse" 6 "and" 7

Eachboxisreferencedbyitsnumbersothestatement d e m o l i s t [ 0 ] wouldget ' l i f e ' , d e m o l i s t [ 1 ] wouldget 4 2 andsoonupto d e m o l i s t [ 5 ] getting 7 .

Morefeaturesoflists
Thenextexampleisjusttoshowalotofotherstufflistscando(foronceIdon'texpectyoutotypeitin,butyoushouldprobablyplayaroundwithlistsuntil youarecomfortablewiththem.).Heregoes:
d e m o l i s t=[ " l i f e " ,4 2 ," t h eu n i v e r s e " ,6 ," a n d " ,7 ] p r i n t" d e m o l i s t=" , d e m o l i s t d e m o l i s t . a p p e n d ( " e v e r y t h i n g " ) p r i n t" a f t e r' e v e r y t h i n g 'w a sa p p e n d e dd e m o l i s ti sn o w : " p r i n td e m o l i s t p r i n t" l e n ( d e m o l i s t )= " ,l e n ( d e m o l i s t ) p r i n t" d e m o l i s t . i n d e x ( 4 2 )= " ,d e m o l i s t . i n d e x ( 4 2 ) p r i n t" d e m o l i s t [ 1 ]= " ,d e m o l i s t [ 1 ] #N e x tw ew i l ll o o pt h r o u g ht h el i s t c=0 w h i l ec<l e n ( d e m o l i s t ) : p r i n t" d e m o l i s t [ " ,c ," ]= " ,d e m o l i s t [ c ] c=c+1 d e ld e m o l i s t [ 2 ] p r i n t" A f t e r' t h eu n i v e r s e 'w a sr e m o v e dd e m o l i s ti sn o w : " p r i n td e m o l i s t i f" l i f e "i nd e m o l i s t :
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 48/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

p r i n t" ' l i f e 'w a sf o u n di nd e m o l i s t " e l s e : p r i n t" ' l i f e 'w a sn o tf o u n di nd e m o l i s t " i f" a m o e b a "i nd e m o l i s t : p r i n t" ' a m o e b a 'w a sf o u n di nd e m o l i s t " i f" a m o e b a "n o ti nd e m o l i s t : p r i n t" ' a m o e b a 'w a sn o tf o u n di nd e m o l i s t " d e m o l i s t . s o r t ( ) p r i n t" T h es o r t e dd e m o l i s ti s " ,d e m o l i s t

Theoutputis:
d e m o l i s t= [ ' l i f e ' ,4 2 ,' t h eu n i v e r s e ' ,6 ,' a n d ' ,7 ] a f t e r' e v e r y t h i n g 'w a sa p p e n d e dd e m o l i s ti sn o w : [ ' l i f e ' ,4 2 ,' t h eu n i v e r s e ' ,6 ,' a n d ' ,7 ,' e v e r y t h i n g ' ] l e n ( d e m o l i s t )=7 d e m o l i s t . i n d e x ( 4 2 )=1 d e m o l i s t [ 1 ]=4 2 d e m o l i s t [0]=l i f e d e m o l i s t [1]=4 2 d e m o l i s t [2]=t h eu n i v e r s e d e m o l i s t [3]=6 d e m o l i s t [4]=a n d d e m o l i s t [5]=7 d e m o l i s t [6]=e v e r y t h i n g A f t e r' t h eu n i v e r s e 'w a sr e m o v e dd e m o l i s ti sn o w : [ ' l i f e ' ,4 2 ,6 ,' a n d ' ,7 ,' e v e r y t h i n g ' ] ' l i f e 'w a sf o u n di nd e m o l i s t ' a m o e b a 'w a sn o tf o u n di nd e m o l i s t T h es o r t e dd e m o l i s ti s[ 6 ,7 ,4 2 ,' a n d ' ,' e v e r y t h i n g ' ,' l i f e ' ]

Thisexampleusesawholebunchofnewfunctions.Noticethatyoucanjust p r i n t awholelist.Nextthe a p p e n d functionisusedtoaddanewitemtotheendof thelist. l e n returnshowmanyitemsareinalist.Thevalidindexes(asinnumbersthatcanbeusedinsideofthe [ ] )ofalistrangefrom0to l e n-1 .The i n d e x functiontellswherethefirstlocationofanitemislocatedinalist.Noticehow d e m o l i s t . i n d e x ( 4 2 ) returns1,andwhen d e m o l i s t [ 1 ] isrunitreturns42.Theline # N e x tw ew i l ll o o pt h r o u g ht h el i s t isajustaremindertotheprogrammer(alsocalleda comment ).Pythonwillignoreanylinesthatstartwitha # .Nextthelines:
c=0 w h i l ec<l e n ( d e m o l i s t ) : p r i n t' d e m o l i s t [ ' ,c ,' ]= ' ,d e m o l i s t [ c ] c=c+1

createavariable c ,whichstartsat0andisincrementeduntilitreachesthelastindexofthelist.Meanwhilethe p r i n t statementprintsouteachelementofthe list.The d e l commandcanbeusedtoremoveagivenelementinalist.Thenextfewlinesusethe i n operatortotestifanelementisinorisnotinalist.The s o r t functionsortsthelist.Thisisusefulifyouneedalistinorderfromsmallestnumbertolargestoralphabetical.Notethatthisrearrangesthelist.In


en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 49/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

summary,foralist,thefollowingoperationsoccur: example
d e m o l i s t [ 2 ] d e m o l i s t [ 2 ]=3 d e ld e m o l i s t [ 2 ] l e n ( d e m o l i s t ) " v a l u e "i nd e m o l i s t " v a l u e "n o ti nd e m o l i s t d e m o l i s t . s o r t ( ) d e m o l i s t . i n d e x ( " v a l u e " )

explanation accessestheelementatindex2 setstheelementatindex2tobe3 removestheelementatindex2 returnsthelengthof d e m o l i s t is Trueif " v a l u e " isanelementin d e m o l i s t is Trueif " v a l u e " isnotanelementin d e m o l i s t sorts d e m o l i s t returnstheindexofthefirstplacethat " v a l u e " occurs

d e m o l i s t . a p p e n d ( " v a l u e " ) addsanelement " v a l u e " attheendofthelist d e m o l i s t . r e m o v e ( " v a l u e " ) removesthefirstoccurrenceofvaluefrom d e m o l i s t (sameas d e ld e m o l i s t [ d e m o l i s t . i n d e x ( " v a l u e " ) ] )

Thisnextexampleusesthesefeaturesinamoreusefulway:
m e n u _ i t e m=0 n a m e l i s t=[ ] w h i l em e n u _ i t e m! =9 : p r i n t" " p r i n t" 1 .P r i n tt h el i s t " p r i n t" 2 .A d dan a m et ot h el i s t " p r i n t" 3 .R e m o v ean a m ef r o mt h el i s t " p r i n t" 4 .C h a n g ea ni t e mi nt h el i s t " p r i n t" 9 .Q u i t " m e n u _ i t e m=i n p u t ( " P i c ka ni t e mf r o mt h em e n u :" ) i fm e n u _ i t e m= =1 : c u r r e n t=0 i fl e n ( n a m e l i s t )>0 : w h i l ec u r r e n t<l e n ( n a m e l i s t ) : p r i n tc u r r e n t ," . " ,n a m e l i s t [ c u r r e n t ] c u r r e n t=c u r r e n t+1 e l s e : p r i n t" L i s ti se m p t y " e l i fm e n u _ i t e m= =2 : n a m e=r a w _ i n p u t ( " T y p ei nan a m et oa d d :" ) n a m e l i s t . a p p e n d ( n a m e ) e l i fm e n u _ i t e m= =3 : d e l _ n a m e=r a w _ i n p u t ( " W h a tn a m ew o u l dy o ul i k et or e m o v e :" ) i fd e l _ n a m ei nn a m e l i s t : #n a m e l i s t . r e m o v e ( d e l _ n a m e )w o u l dw o r kj u s ta sf i n e i t e m _ n u m b e r=n a m e l i s t . i n d e x ( d e l _ n a m e ) d e ln a m e l i s t [ i t e m _ n u m b e r ]
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 50/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

#T h ec o d ea b o v eo n l yr e m o v e st h ef i r s to c c u r r e n c eo f #t h en a m e . T h ec o d eb e l o wf r o mG e r a l dr e m o v e sa l l . #w h i l ed e l _ n a m ei nn a m e l i s t : # i t e m _ n u m b e r=n a m e l i s t . i n d e x ( d e l _ n a m e ) # d e ln a m e l i s t [ i t e m _ n u m b e r ] e l s e : p r i n td e l _ n a m e ," w a sn o tf o u n d " e l i fm e n u _ i t e m= =4 : o l d _ n a m e=r a w _ i n p u t ( " W h a tn a m ew o u l dy o ul i k et oc h a n g e :" ) i fo l d _ n a m ei nn a m e l i s t : i t e m _ n u m b e r=n a m e l i s t . i n d e x ( o l d _ n a m e ) n e w _ n a m e=r a w _ i n p u t ( " W h a ti st h en e wn a m e :" ) n a m e l i s t [ i t e m _ n u m b e r ]=n e w _ n a m e e l s e : p r i n to l d _ n a m e ," w a sn o tf o u n d " p r i n t" G o o d b y e "

Andhereispartoftheoutput:
1 .P r i n tt h el i s t 2 .A d dan a m et ot h el i s t 3 .R e m o v ean a m ef r o mt h el i s t 4 .C h a n g ea ni t e mi nt h el i s t 9 .Q u i t P i c ka ni t e mf r o mt h em e n u :2 T y p ei nan a m et oa d d :J a c k P i c ka ni t e mf r o mt h em e n u :2 T y p ei nan a m et oa d d :J i l l P i c ka ni t e mf r o mt h em e n u :1 0.J a c k 1.J i l l P i c ka ni t e mf r o mt h em e n u :3 W h a tn a m ew o u l dy o ul i k et or e m o v e :J a c k P i c ka ni t e mf r o mt h em e n u :4 W h a tn a m ew o u l dy o ul i k et oc h a n g e :J i l l W h a ti st h en e wn a m e :J i l lP e t e r s P i c ka ni t e mf r o mt h em e n u :1 0.J i l lP e t e r s P i c ka ni t e mf r o mt h em e n u :9 G o o d b y e

en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version

51/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

Thatwasalongprogram.Let'stakealookatthesourcecode.Theline n a m e l i s t=[ ] makesthevariable n a m e l i s t alistwithnoitems(orelements).Thenext importantlineis w h i l em e n u _ i t e m! =9 : .Thislinestartsaloopthatallowsthemenusystemforthisprogram.Thenextfewlinesdisplayamenuanddecidewhich partoftheprogramtorun. Thesection


c u r r e n t=0 i fl e n ( n a m e l i s t )>0 : w h i l ec u r r e n t<l e n ( n a m e l i s t ) : p r i n tc u r r e n t ," . " ,n a m e l i s t [ c u r r e n t ] c u r r e n t=c u r r e n t+1 e l s e : p r i n t" L i s ti se m p t y "

goesthroughthelistandprintseachname. l e n ( n a m e l i s t ) tellshowmanyitemsareinthelist.If l e n returns 0 ,thenthelistisempty. Then,afewlineslater,thestatement n a m e l i s t . a p p e n d ( n a m e ) appears.Itusesthe a p p e n d functiontoaddanitemtotheendofthelist.Jumpdownanothertwo lines,andnoticethissectionofcode:


i t e m _ n u m b e r=n a m e l i s t . i n d e x ( d e l _ n a m e ) d e ln a m e l i s t [ i t e m _ n u m b e r ]

Herethe i n d e x functionisusedtofindtheindexvaluethatwillbeusedlatertoremovetheitem. d e ln a m e l i s t [ i t e m _ n u m b e r ] isusedtoremoveaelementofthelist. Thenextsection


o l d _ n a m e=r a w _ i n p u t ( " W h a tn a m ew o u l dy o ul i k et oc h a n g e :" ) i fo l d _ n a m ei nn a m e l i s t : i t e m _ n u m b e r=n a m e l i s t . i n d e x ( o l d _ n a m e ) n e w _ n a m e=r a w _ i n p u t ( " W h a ti st h en e wn a m e :" ) n a m e l i s t [ i t e m _ n u m b e r ]=n e w _ n a m e e l s e : p r i n to l d _ n a m e ," w a sn o tf o u n d "

uses i n d e x tofindthe i t e m _ n u m b e r andthenputs n e w _ n a m e wherethe o l d _ n a m e was. Congratulations,withlistsunderyourbelt,younowknowenoughofthelanguagethatyoucoulddoanycomputationsthatacomputercando(thisis technicallyknownasTuringCompleteness).Ofcourse,therearestillmanyfeaturesthatareusedtomakeyourlifeeasier.

Examples
test.py
# #T h i sp r o g r a mr u n sat e s to fk n o w l e d g e
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 52/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

#F i r s tg e tt h et e s tq u e s t i o n s #L a t e rt h i sw i l lb em o d i f i e dt ou s ef i l ei o . d e fg e t _ q u e s t i o n s ( ) : #n o t i c eh o wt h ed a t ai ss t o r e da sal i s to fl i s t s r e t u r n[ [ " W h a tc o l o ri st h ed a y t i m es k yo nac l e a rd a y ?" ," b l u e " ] , [ " W h a ti st h ea n s w e rt ol i f e ,t h eu n i v e r s ea n de v e r y t h i n g ?" ," 4 2 " ] , [ " W h a ti sat h r e el e t t e rw o r df o rm o u s et r a p ?" ," c a t " ] ] #T h i sw i l lt e s tas i n g l eq u e s t i o n #i tt a k e sas i n g l eq u e s t i o ni n #i tr e t u r n sT r u ei ft h eu s e rt y p e dt h ec o r r e c ta n s w e r ,o t h e r w i s eF a l s e d e fc h e c k _ q u e s t i o n ( q u e s t i o n _ a n d _ a n s w e r ) : #e x t r a c tt h eq u e s t i o na n dt h ea n s w e rf r o mt h el i s t q u e s t i o n=q u e s t i o n _ a n d _ a n s w e r [ 0 ] a n s w e r=q u e s t i o n _ a n d _ a n s w e r [ 1 ] #g i v et h eq u e s t i o nt ot h eu s e r g i v e n _ a n s w e r=r a w _ i n p u t ( q u e s t i o n ) #c o m p a r et h eu s e r ' sa n s w e rt ot h et e s t e r sa n s w e r i fa n s w e r= =g i v e n _ a n s w e r : p r i n t" C o r r e c t " r e t u r nT r u e e l s e : p r i n t" I n c o r r e c t ,c o r r e c tw a s : " ,a n s w e r r e t u r nF a l s e #T h i sw i l lr u nt h r o u g ha l lt h eq u e s t i o n s d e fr u n _ t e s t ( q u e s t i o n s ) : i fl e n ( q u e s t i o n s )= =0 : p r i n t" N oq u e s t i o n sw e r eg i v e n . " #t h er e t u r ne x i t st h ef u n c t i o n r e t u r n i n d e x=0 r i g h t=0 w h i l ei n d e x<l e n ( q u e s t i o n s ) : #C h e c kt h eq u e s t i o n i fc h e c k _ q u e s t i o n ( q u e s t i o n s [ i n d e x ] ) : r i g h t=r i g h t+1 i n d e x=i n d e x+1 #g ot ot h en e x tq u e s t i o n e l s e : i n d e x=i n d e x+1 #n o t i c et h eo r d e ro ft h ec o m p u t a t i o n ,f i r s tm u l t i p l y ,t h e nd i v i d e p r i n t" Y o ug o t " ,r i g h t*1 0 0/l e n ( q u e s t i o n s ) , \ " %r i g h to u to f " ,l e n ( q u e s t i o n s ) #n o wl e t ' sr u nt h eq u e s t i o n s r u n _ t e s t ( g e t _ q u e s t i o n s ( ) )

Thevalues T r u e and F a l s e pointto1and0,respectively.Theyareoftenusedinsanitychecks,loopconditionsetc.Youwilllearnmoreaboutthisalittlebitlater (chapterBooleanExpressions).

en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version

53/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

SampleOutput:
W h a tc o l o ri st h ed a y t i m es k yo nac l e a rd a y ? g r e e n I n c o r r e c t ,c o r r e c tw a s :b l u e W h a ti st h ea n s w e rt ol i f e ,t h eu n i v e r s ea n de v e r y t h i n g ? 4 2 C o r r e c t W h a ti sat h r e el e t t e rw o r df o rm o u s et r a p ? c a t C o r r e c t Y o ug o t6 6%r i g h to u to f3

Exercises
Expandthetest.pyprogramsoithasamenugivingtheoptionoftakingthetest,viewingthelistofquestionsandanswers,andanoptiontoquit.Also,adda newquestiontoask,"Whatnoisedoesatrulyadvancedmachinemake?"withtheanswerof"ping". Solution Expandthetest.pyprogramsoithasmenugivingtheoptionoftakingthetest,viewingthelistofquestionsandanswers,andanoptiontoquit.Also,adda newquestiontoask,"Whatnoisedoesatrulyadvancedmachinemake?"withtheanswerof"ping".

# #T h i sp r o g r a mr u n sat e s to fk n o w l e d g e q u e s t i o n s=[ [ " W h a tc o l o ri st h ed a y t i m es k yo nac l e a rd a y ?" ," b l u e " ] , [ " W h a ti st h ea n s w e rt ol i f e ,t h eu n i v e r s ea n de v e r y t h i n g ?" ," 4 2 " ] , [ " W h a ti sat h r e el e t t e rw o r df o rm o u s et r a p ?" ," c a t " ] , [ " W h a tn o i s ed o e sat r u l ya d v a n c e dm a c h i n em a k e ? " ," p i n g " ] ] #T h i sw i l lt e s tas i n g l eq u e s t i o n #i tt a k e sas i n g l eq u e s t i o ni n #i tr e t u r n sT r u ei ft h eu s e rt y p e dt h ec o r r e c ta n s w e r ,o t h e r w i s eF a l s e d e fc h e c k _ q u e s t i o n ( q u e s t i o n _ a n d _ a n s w e r ) : #e x t r a c tt h eq u e s t i o na n dt h ea n s w e rf r o mt h el i s t q u e s t i o n=q u e s t i o n _ a n d _ a n s w e r [ 0 ] a n s w e r=q u e s t i o n _ a n d _ a n s w e r [ 1 ] #g i v et h eq u e s t i o nt ot h eu s e r g i v e n _ a n s w e r=r a w _ i n p u t ( q u e s t i o n ) #c o m p a r et h eu s e r ' sa n s w e rt ot h et e s t e r sa n s w e r i fa n s w e r= =g i v e n _ a n s w e r : p r i n t" C o r r e c t " r e t u r nT r u e e l s e : p r i n t" I n c o r r e c t ,c o r r e c tw a s : " ,a n s w e r r e t u r nF a l s e #T h i sw i l lr u nt h r o u g ha l lt h eq u e s t i o n s

en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version

54/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

d e fr u n _ t e s t ( q u e s t i o n s ) : i fl e n ( q u e s t i o n s )= =0 : p r i n t" N oq u e s t i o n sw e r eg i v e n . " #t h er e t u r ne x i t st h ef u n c t i o n r e t u r n i n d e x=0 r i g h t=0 w h i l ei n d e x<l e n ( q u e s t i o n s ) : #C h e c kt h eq u e s t i o n i fc h e c k _ q u e s t i o n ( q u e s t i o n s [ i n d e x ] ) : r i g h t=r i g h t+1 #g ot ot h en e x tq u e s t i o n i n d e x=i n d e x+1 #n o t i c et h eo r d e ro ft h ec o m p u t a t i o n ,f i r s tm u l t i p l y ,t h e nd i v i d e p r i n t( " Y o ug o t " ,r i g h t*1 0 0/l e n ( q u e s t i o n s ) , " %r i g h to u to f " ,l e n ( q u e s t i o n s ) ) # s h o w i n gal i s to fq u e s t i o n sa n da n s w e r s d e fs h o w q u e s t i o n s ( q u e s t i o n s ) : q=0 w h i l eq<l e n ( q u e s t i o n s ) : a=0 p r i n t" Q : ",q u e s t i o n s [ q ] [ a ] a=1 p r i n t" A : ",q u e s t i o n s [ q ] [ a ] q=q+1 #n o wl e t ' sd e f i n et h em e n uf u n c t i o n d e fm e n u ( ) : p r i n t" " p r i n t" M e n u : " p r i n t" 1-T a k et h et e s t " p r i n t" 2-V i e wal i s to fq u e s t i o n sa n da n s w e r s " p r i n t" 3-V i e wt h em e n u " p r i n t" 5-Q u i t " p r i n t" " c h o i c e=" 3 " w h i l ec h o i c e! =" 5 " : i fc h o i c e= =" 1 " : r u n _ t e s t ( q u e s t i o n s ) e l i fc h o i c e= =" 2 " : s h o w q u e s t i o n s ( q u e s t i o n s ) e l i fc h o i c e= =" 3 " : m e n u ( ) p r i n t c h o i c e=r a w _ i n p u t ( " C h o o s ey o u ro p t i o nf r o mt h em e n ua b o v e :" )

ForLoops
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 55/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

Andhereisthenewtypingexerciseforthischapter:
o n e t o t e n=r a n g e ( 1 ,1 1 ) f o rc o u n ti no n e t o t e n : p r i n tc o u n t

andtheeverpresentoutput:
1 2 3 4 5 6 7 8 9 1 0

Theoutputlooksawfullyfamiliarbuttheprogramcodelooksdifferent.Thefirstlineusesthe r a n g e function.The r a n g e functionusestwoargumentslikethis r a n g e ( s t a r t ,f i n i s h ) . s t a r t isthefirstnumberthatisproduced. f i n i s h isonelargerthanthelastnumber.Notethatthisprogramcouldhavebeendoneinashorter way:


f o rc o u n ti nr a n g e ( 1 ,1 1 ) : p r i n tc o u n t

Herearesomeexamplestoshowwhathappenswiththe r a n g e command:
> > >r a n g e ( 1 ,1 0 ) [ 1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ] > > >r a n g e ( 3 2 ,2 0 ) [ 3 2 ,3 1 ,3 0 ,2 9 ,2 8 ,2 7 ,2 6 ,2 5 ,2 4 ,2 3 ,2 2 ,2 1 ] > > >r a n g e ( 5 , 2 1 ) [ 5 ,6 ,7 ,8 ,9 ,1 0 ,1 1 ,1 2 ,1 3 ,1 4 ,1 5 ,1 6 ,1 7 ,1 8 ,1 9 ,2 0 ] > > >r a n g e ( 5 ) [ 0 ,1 ,2 ,3 ,4 ] > > >r a n g e ( 2 1 ,5 ) [ ]

Thenextline f o rc o u n ti no n e t o t e n : usesthe f o r controlstructure.A f o r controlstructurelookslike f o rv a r i a b l ei nl i s t : . l i s t isgonethroughstartingwiththefirst elementofthelistandgoingtothelast.As f o r goesthrougheachelementinalistitputseachinto v a r i a b l e .Thatallows v a r i a b l e tobeusedineachsuccessive timethe f o r loopisrunthrough.Hereisanotherexample(youdon'thavetotypethis)todemonstrate:
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 56/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

d e m o l i s t=[ ' l i f e ' ,4 2 ,' t h eu n i v e r s e ' ,6 ,' a n d ' ,9 ,' e v e r y t h i n g ' ] f o ri t e mi nd e m o l i s t : p r i n t" T h eC u r r e n ti t e mi s : " , p r i n ti t e m

Theoutputis:
T h eC u r r e n ti t e mi s :l i f e T h eC u r r e n ti t e mi s :4 2 T h eC u r r e n ti t e mi s :t h eu n i v e r s e T h eC u r r e n ti t e mi s :6 T h eC u r r e n ti t e mi s :a n d T h eC u r r e n ti t e mi s :9 T h eC u r r e n ti t e mi s :e v e r y t h i n g

Noticehowthe f o r loopgoesthroughandsetsitemtoeachelementinthelist.Noticehowifyoudon'twant p r i n t togotothenextlineaddacommaatthe endofthestatement(i.e.ifyouwanttoprintsomethingelseonthatline).So,whatis f o r goodfor?Thefirstuseistogothroughalltheelementsofalistand dosomethingwitheachofthem.Here'saquickwaytoaddupalltheelements:


l i s t=[ 2 ,4 ,6 ,8 ] s u m=0 f o rn u mi nl i s t : s u m=s u m+n u m p r i n t" T h es u mi s : " ,s u m

withtheoutputsimplybeing:
T h es u mi s :2 0

Oryoucouldwriteaprogramtofindoutifthereareanyduplicatesinalistlikethisprogramdoes:
l i s t=[ 4 ,5 ,7 ,8 ,9 ,1 ,0 ,7 ,1 0 ] l i s t . s o r t ( ) p r e v=l i s t [ 0 ] d e ll i s t [ 0 ] f o ri t e mi nl i s t : i fp r e v= =i t e m : p r i n t" D u p l i c a t eo f " ,p r e v ," f o u n d " p r e v=i t e m

andforgoodmeasure:

en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version

57/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

D u p l i c a t eo f7F o u n d

Okay,sohowdoesitwork?Hereisaspecialdebuggingversiontohelpyouunderstand(youdon'tneedtotypethisin):
l=[ 4 ,5 ,7 ,8 ,9 ,1 ,0 ,7 ,1 0 ] p r i n t" l=[ 4 ,5 ,7 ,8 ,9 ,1 ,0 ,7 ,1 0 ] " ," \ t \ t l : " ,l l . s o r t ( ) p r i n t" l . s o r t ( ) " ," \ t \ t l : " ,l p r e v=l [ 0 ] p r i n t" p r e v=l [ 0 ] " ," \ t \ t p r e v : " ,p r e v d e ll [ 0 ] p r i n t" d e ll [ 0 ] " ," \ t \ t l : " ,l f o ri t e mi nl : i fp r e v= =i t e m : p r i n t" D u p l i c a t eo f " ,p r e v ," f o u n d " p r i n t" i fp r e v= =i t e m : " ," \ t \ t p r e v : " ,p r e v ," \ t i t e m : " ,i t e m p r e v=i t e m p r i n t" p r e v=i t e m " ," \ t \ t p r e v : " ,p r e v ," \ t i t e m : " ,i t e m

withtheoutputbeing:
l=[ 4 ,5 ,7 ,8 ,9 ,1 ,0 ,7 ,1 0 ] l :[ 4 ,5 ,7 ,8 ,9 ,1 ,0 ,7 ,1 0 ] l . s o r t ( ) l :[ 0 ,1 ,4 ,5 ,7 ,7 ,8 ,9 ,1 0 ] p r e v=l [ 0 ] p r e v :0 d e ll [ 0 ] l :[ 1 ,4 ,5 ,7 ,7 ,8 ,9 ,1 0 ] i fp r e v= =i t e m : p r e v :0 i t e m :1 p r e v=i t e m p r e v :1 i t e m :1 i fp r e v= =i t e m : p r e v :1 i t e m :4 p r e v=i t e m p r e v :4 i t e m :4 i fp r e v= =i t e m : p r e v :4 i t e m :5 p r e v=i t e m p r e v :5 i t e m :5 i fp r e v= =i t e m : p r e v :5 i t e m :7 p r e v=i t e m p r e v :7 i t e m :7 D u p l i c a t eo f7f o u n d i fp r e v= =i t e m : p r e v :7 i t e m :7 p r e v=i t e m p r e v :7 i t e m :7 i fp r e v= =i t e m : p r e v :7 i t e m :8 p r e v=i t e m p r e v :8 i t e m :8 i fp r e v= =i t e m : p r e v :8 i t e m :9 p r e v=i t e m p r e v :9 i t e m :9 i fp r e v= =i t e m : p r e v :9 i t e m :1 0 p r e v=i t e m p r e v :1 0 i t e m :1 0

ThereasonIputsomany p r i n t statementsinthecodewassothatyoucanseewhatishappeningineachline.(Bytheway,ifyoucan'tfigureoutwhya programisnotworking,tryputtinginlotsofprintstatementssoyoucanseewhatishappening.)Firsttheprogramstartswithaboringoldlist.Nextthe programsortsthelist.Thisissothatanyduplicatesgetputnexttoeachother.Theprogramtheninitializesa p r e v (ious)variable.Nextthefirstelementofthe


en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 58/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

listisdeletedsothatthefirstitemisnotincorrectlythoughttobeaduplicate.Nexta f o r loopisgoneinto.Eachitemofthelistischeckedtoseeifitisthe sameastheprevious.Ifitisaduplicatewasfound.Thevalueof p r e v isthenchangedsothatthenexttimethe f o r loopisrunthrough p r e v isthepreviousitem tothecurrent.Sureenough,the7isfoundtobeaduplicate.(Noticehow \ t isusedtoprintatab.) Theotherwaytouse f o r loopsistodosomethingacertainnumberoftimes.Hereissomecodetoprintoutthefirst9numbersoftheFibonacciseries:
a=1 b=1 f o rci nr a n g e ( 1 ,1 0 ) : p r i n ta , n=a+b a=b b=n

withthesurprisingoutput:
1123581 32 13 4

Everythingthatcanbedonewith f o r loopscanalsobedonewith w h i l e loopsbut f o r loopsgiveaneasywaytogothroughalltheelementsinalistortodo somethingacertainnumberoftimes.

BooleanExpressions
Hereisalittleexampleofbooleanexpressions(youdon'thavetotypeitin):
a=6 b=7 c=4 2 p r i n t1 ,a= =6 p r i n t2 ,a= =7 p r i n t3 ,a= =6a n db= =7 p r i n t4 ,a= =7a n db= =7 p r i n t5 ,n o ta= =7a n db= =7 p r i n t6 ,a= =7o rb= =7 p r i n t7 ,a= =7o rb= =6 p r i n t8 ,n o t( a= =7a n db= =6 ) p r i n t9 ,n o ta= =7a n db= =6

Withtheoutputbeing:
1T r u e 2F a l s e 3T r u e 4F a l s e
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 59/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

5T r u e 6T r u e 7F a l s e 8T r u e 9F a l s e

Whatisgoingon?Theprogramconsistsofabunchoffunnylooking p r i n t statements.Each p r i n t statementprintsanumberandanexpression.Thenumberis tohelpkeeptrackofwhichstatementIamdealingwith.Noticehoweachexpressionendsupbeingeither F a l s e or T r u e .InPython,falsecanalsobewrittenas 0andtrueas1. Thelines:


p r i n t1 ,a= =6 p r i n t2 ,a= =7

printouta T r u e anda F a l s e respectivelyjustasexpectedsincethefirstistrueandthesecondisfalse.Thethirdprint, p r i n t3 ,a= =6a n db= =7 ,isalittle different.Theoperator a n d meansifboththestatementbeforeandthestatementafteraretruethenthewholeexpressionistrueotherwisethewhole expressionisfalse.Thenextline, p r i n t4 ,a= =7a n db= =7 ,showshowifpartofan a n d expressionisfalse,thewholethingisfalse.Thebehaviorof a n d canbe summarizedasfollows: expression result true a n d true true

true a n d false false false a n d true false false a n d false false NoticethatifthefirstexpressionisfalsePythondoesnotcheckthesecondexpressionsinceitknowsthewholeexpressionisfalse. Thenextline, p r i n t5 ,n o ta= =7a n db= =7 ,usesthe n o t operator. n o t justgivestheoppositeoftheexpression.(Theexpressioncouldberewrittenas p r i n t5 ,a! = 7a n db= =7 ).Hereisthetable: expression result
n o t true n o t false

false true

Thetwofollowinglines, p r i n t6 ,a= =7o rb= =7 and p r i n t7 ,a= =7o rb= =6 ,usethe o r operator.The o r operatorreturnstrueifthefirstexpressionistrue,orif thesecondexpressionistrueorbotharetrue.Ifneitheraretrueitreturnsfalse.Here'sthetable:

en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version

60/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

expression result true o r true true

true o r false true false o r true true false o r false false NoticethatifthefirstexpressionistruePythondoesn'tcheckthesecondexpressionsinceitknowsthewholeexpressionistrue.Thisworkssince o r istrueifat leastonehalfoftheexpressionistrue.Thefirstpartistruesothesecondpartcouldbeeitherfalseortrue,butthewholeexpressionisstilltrue. Thenexttwolines, p r i n t8 ,n o t( a= =7a n db= =6 ) and p r i n t9 ,n o ta= =7a n db= =6 ,showthatparenthesescanbeusedtogroupexpressionsandforceonepart tobeevaluatedfirst.Noticethattheparentheseschangedtheexpressionfromfalsetotrue.Thisoccurredsincetheparenthesesforcedthe n o t toapplytothe wholeexpressioninsteadofjustthe a= =7 portion. Hereisanexampleofusingabooleanexpression:
l i s t=[ " L i f e " ," T h eU n i v e r s e " ," E v e r y t h i n g " ," J a c k " ," J i l l " ," L i f e " ," J i l l " ] #m a k eac o p yo ft h el i s t .S e et h eM o r eo nL i s t sc h a p t e rt oe x p l a i nw h a t[ : ]m e a n s . c o p y=l i s t [ : ] #s o r tt h ec o p y c o p y . s o r t ( ) p r e v=c o p y [ 0 ] d e lc o p y [ 0 ] c o u n t=0 #g ot h r o u g ht h el i s ts e a r c h i n gf o ram a t c h w h i l ec o u n t<l e n ( c o p y )a n dc o p y [ c o u n t ]! =p r e v : p r e v=c o p y [ c o u n t ] c o u n t=c o u n t+1 #I fam a t c hw a sn o tf o u n dt h e nc o u n tc a n ' tb e<l e n #s i n c et h ew h i l el o o pc o n t i n u e sw h i l ec o u n ti s<l e n #a n dn om a t c hi sf o u n d i fc o u n t<l e n ( c o p y ) : p r i n t" F i r s tM a t c h : " ,p r e v

Andhereistheoutput:
F i r s tM a t c h :J i l l

Thisprogramworksbycontinuingtocheckformatch w h i l ec o u n t<l e n ( c o p y )a n dc o p y [ c o u n t ]i sn o te q u a lt op r e v .Wheneither c o u n t isgreaterthanthelastindexof c o p y oramatchhasbeenfoundthe a n d isnolongertruesotheloopexits.The i f simplycheckstomakesurethatthe w h i l e exitedbecauseamatchwasfound.


en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 61/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

Theother"trick"of a n d isusedinthisexample.Ifyoulookatthetablefor a n d noticethatthethirdentryis"falseandwon'tcheck".If c o u n t> =l e n ( c o p y ) (inother words c o u n t<l e n ( c o p y ) isfalse)then c o p y [ c o u n t ] isneverlookedat.ThisisbecausePythonknowsthatifthefirstisfalsethentheycan'tbothbetrue.Thisis knownasashortcircuitandisusefulifthesecondhalfofthe a n d willcauseanerrorifsomethingiswrong.Iusedthefirstexpression(c o u n t<l e n ( c o p y ) )tocheck andseeif c o u n t wasavalidindexfor c o p y .(Ifyoudon'tbelievemeremovethematches"Jill"and"Life",checkthatitstillworksandthenreversetheorderof c o u n t<l e n ( c o p y )a n dc o p y [ c o u n t ]! =p r e v to c o p y [ c o u n t ]! =p r e va n dc o u n t<l e n ( c o p y ) .) Booleanexpressionscanbeusedwhenyouneedtochecktwoormoredifferentthingsatonce.

AnoteonBooleanOperators
Acommonmistakeforpeoplenewtoprogrammingisamisunderstandingofthewaythatbooleanoperatorsworks,whichstemsfromthewaythepython interpreterreadstheseexpressions.Forexample,afterinitiallylearningabout"and"and"or"statements,onemightassumethattheexpression x= =( ' a 'o r ' b ' ) wouldchecktoseeifthevariable x wasequivalenttooneofthestrings ' a ' or ' b ' .Thisisnotso.ToseewhatI'mtalkingabout,startaninteractivesession withtheinterpreterandenterthefollowingexpressions:
> > >' a '= =( ' a 'o r' b ' ) > > >' b '= =( ' a 'o r' b ' ) > > >' a '= =( ' a 'a n d' b ' ) > > >' b '= =( ' a 'a n d' b ' )

Andthiswillbetheunintuitiveresult:
> > >' a '= =( ' a 'o r' b ' ) T r u e > > >' b '= =( ' a 'o r' b ' ) F a l s e > > >' a '= =( ' a 'a n d' b ' ) F a l s e > > >' b '= =( ' a 'a n d' b ' ) T r u e

Atthispoint,the a n d and o r operatorsseemtobebroken.Itdoesn'tmakesensethat,forthefirsttwoexpressions, ' a ' isequivalentto ' a ' or ' b ' while ' b ' isnot. Furthermore,itdoesn'tmakeanysensethat'b'isequivalentto ' a ' and ' b ' .Afterexaminingwhattheinterpreterdoeswithbooleanoperators,theseresultsdo infactexactlywhatyouareaskingofthem,it'sjustnotthesameaswhatyouthinkyouareasking. WhenthePythoninterpreterlooksatan o r expression,ittakesthefirststatementandcheckstoseeifitistrue.Ifthefirststatementistrue,thenPython returnsthatobject'svaluewithoutcheckingthesecondstatement.Thisisbecauseforan o r expression,thewholethingistrueifoneofthevaluesistruethe programdoesnotneedtobotherwiththesecondstatement.Ontheotherhand,ifthefirstvalueisevaluatedasfalsePythonchecksthesecondhalfand returnsthatvalue.Thatsecondhalfdeterminesthetruthvalueofthewholeexpressionsincethefirsthalfwasfalse.This"laziness"onthepartofthe interpreteriscalled"shortcircuiting"andisacommonwayofevaluatingbooleanexpressionsinmanyprogramminglanguages. Similarly,foran a n d expression,Pythonusesashortcircuittechniquetospeedtruthvalueevaluation.Ifthefirststatementisfalsethenthewholethingmust befalse,soitreturnsthatvalue.Otherwiseifthefirstvalueistrueitchecksthesecondandreturnsthatvalue.
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 62/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

Onethingtonoteatthispointisthatthebooleanexpressionreturnsavalueindicating T r u e or F a l s e ,butthatPythonconsidersanumberofdifferentthingsto haveatruthvalueassignedtothem.Tocheckthetruthvalueofanygivenobject x ,youcanusethefunction b o o l ( x ) toseeitstruthvalue.Belowisatablewith examplesofthetruthvaluesofvariousobjects: True True 1 False 0 False

Numbersotherthanzero Thestring'None' Nonemptystrings Nonemptylists Nonemptydictionaries Emptystrings Emptylists Emptydictionaries

Nowitispossibletounderstandtheperplexingresultsweweregettingwhenwetestedthosebooleanexpressionsbefore.Let'stakealookatwhatthe interpreter"sees"asitgoesthroughthatcode: Firstcase:


> > >' a '= =( ' a 'o r' b ' ) #L o o ka tp a r e n t h e s e sf i r s t ,s oe v a l u a t ee x p r e s s i o n" ( ' a 'o r' b ' ) " #' a 'i san o n e m p t ys t r i n g ,s ot h ef i r s tv a l u ei sT r u e #R e t u r nt h a tf i r s tv a l u e :' a ' > > >' a '= =' a ' #t h es t r i n g' a 'i se q u i v a l e n tt ot h es t r i n g' a ' ,s oe x p r e s s i o ni sT r u e T r u e

Secondcase:
> > >' b '= =( ' a 'o r' b ' ) #L o o ka tp a r e n t h e s e sf i r s t ,s oe v a l u a t ee x p r e s s i o n" ( ' a 'o r' b ' ) " #' a 'i san o n e m p t ys t r i n g ,s ot h ef i r s tv a l u ei sT r u e #R e t u r nt h a tf i r s tv a l u e :' a ' > > >' b '= =' a ' #t h es t r i n g' b 'i sn o te q u i v a l e n tt ot h es t r i n g' a ' ,s oe x p r e s s i o ni sF a l s e F a l s e

Thirdcase:
> > >' a '= =( ' a 'a n d' b ' )#L o o ka tp a r e n t h e s e sf i r s t ,s oe v a l u a t ee x p r e s s i o n" ( ' a 'a n d' b ' ) " #' a 'i san o n e m p t ys t r i n g ,s ot h ef i r s tv a l u ei sT r u e ,e x a m i n es e c o n dv a l u e #' b 'i san o n e m p t ys t r i n g ,s os e c o n dv a l u ei sT r u e #R e t u r nt h a ts e c o n dv a l u ea sr e s u l to fw h o l ee x p r e s s i o n :' b ' > > >' a '= =' b ' #t h es t r i n g' a 'i sn o te q u i v a l e n tt ot h es t r i n g' b ' ,s oe x p r e s s i o ni sF a l s e F a l s e
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 63/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

Fourthcase:
> > >' b '= =( ' a 'a n d' b ' )#L o o ka tp a r e n t h e s e sf i r s t ,s oe v a l u a t ee x p r e s s i o n" ( ' a 'a n d' b ' ) " #' a 'i san o n e m p t ys t r i n g ,s ot h ef i r s tv a l u ei sT r u e ,e x a m i n es e c o n dv a l u e #' b 'i san o n e m p t ys t r i n g ,s os e c o n dv a l u ei sT r u e #R e t u r nt h a ts e c o n dv a l u ea sr e s u l to fw h o l ee x p r e s s i o n :' b ' > > >' b '= =' b ' #t h es t r i n g' b 'i se q u i v a l e n tt ot h es t r i n g' b ' ,s oe x p r e s s i o ni sT r u e T r u e

SoPythonwasreallydoingitsjobwhenitgavethoseapparentlybogusresults.Asmentionedpreviously,theimportantthingistorecognizewhatvalueyour booleanexpressionwillreturnwhenitisevaluated,becauseitisn'talwaysobvious. Goingbacktothoseinitialexpressions,thisishowyouwouldwritethemoutsotheybehavedinawaythatyouwant:


> > >' a '= =' a 'o r' a '= =' b ' T r u e > > >' b '= =' a 'o r' b '= =' b ' T r u e > > >' a '= =' a 'a n d' a '= =' b ' F a l s e > > >' b '= =' a 'a n d' b '= =' b ' F a l s e

WhenthesecomparisonsareevaluatedtheyreturntruthvaluesintermsofTrueorFalse,notstrings,sowegettheproperresults.

Examples
password1.py
# #T h i sp r o g r a m sa s k sau s e rf o ran a m ea n dap a s s w o r d . #I tt h e nc h e c k st h e mt om a k es u r et h eu s e ri sa l l o w e di n . n a m e=r a w _ i n p u t ( " W h a ti sy o u rn a m e ?" ) p a s s w o r d=r a w _ i n p u t ( " W h a ti st h ep a s s w o r d ?" ) i fn a m e= =" J o s h "a n dp a s s w o r d= =" F r i d a y " : p r i n t" W e l c o m eJ o s h " e l i fn a m e= =" F r e d "a n dp a s s w o r d= =" R o c k " : p r i n t" W e l c o m eF r e d " e l s e : p r i n t" Id o n ' tk n o wy o u . "

Sampleruns
W h a ti sy o u rn a m e ?J o s h
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 64/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

W h a ti st h ep a s s w o r d ?F r i d a y W e l c o m eJ o s h

W h a ti sy o u rn a m e ?B i l l W h a ti st h ep a s s w o r d ?M o n e y Id o n ' tk n o wy o u .

Exercises
Writeaprogramthathasauserguessyourname,buttheyonlyget3chancestodosountiltheprogramquits. Solution Writeaprogramthathasauserguessyourname,buttheyonlyget3chancestodosountiltheprogramquits.

p r i n t" T r yt og u e s sm yn a m e ! " c o u n t=3 n a m e=" T o n y " g u e s s=r a w _ i n p u t ( " W h a ti sm yn a m e ?" ) w h i l ec o u n t>1a n dg u e s s! =n a m e : p r i n t" Y o ua r ew r o n g ! " g u e s s=r a w _ i n p u t ( " W h a ti sm yn a m e ?" ) c o u n t=c o u n t-1 i fg u e s s! =n a m e : p r i n t" Y o ua r ew r o n g ! "#t h i sm e s s a g ei s n ' tp r i n t e di nt h et h i r dc h a n c e ,s ow ep r i n ti tn o w p r i n t" Y o ur a no u to fc h a n c e s . " q u i t e l s e : p r i n t" Y e s !M yn a m ei s " ,n a m e+" ! "

Dictionaries
Thischapterisaboutdictionaries.Ifyouopenadictionary,youshouldnoticeeveryentryconsistsoftwoparts,awordandtheword'sdefinition.Thewordis thekeytofindingoutwhatawordmeans,andwhatthewordmeansisconsideredthevalueforthatkey.InPython,dictionarieshavekeysandvalues.Keys areusedtofindvalues.Hereisanexampleofadictionaryinuse:
d e fp r i n t _ m e n u ( ) : p r i n t' 1 .P r i n tD i c t i o n a r y ' p r i n t' 2 .A d dd e f i n i t i o n ' p r i n t' 3 .R e m o v ew o r d ' p r i n t' 4 .L o o k u pw o r d '
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 65/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

p r i n t' 5 .Q u i t ' p r i n t w o r d s={ } m e n u _ c h o i c e=0 p r i n t _ m e n u ( ) w h i l em e n u _ c h o i c e! =5 : m e n u _ c h o i c e=i n p u t ( " T y p ei nan u m b e r( 1 5 ) :" ) i fm e n u _ c h o i c e= =1 : p r i n t" D e f i n i t i o n s : " f o rxi nw o r d s . k e y s ( ) : p r i n tx ," :" ,w o r d s [ x ] p r i n t e l i fm e n u _ c h o i c e= =2 : p r i n t" A d dd e f i n i t i o n " n a m e=r a w _ i n p u t ( " W o r d :" ) m e a n s=r a w _ i n p u t ( " D e f i n i t i o n :" ) w o r d s [ n a m e ]=m e a n s e l i fm e n u _ c h o i c e= =3 : p r i n t" R e m o v ew o r d " n a m e=r a w _ i n p u t ( " W o r d :" ) i fn a m ei nw o r d s : d e lw o r d s [ n a m e ] p r i n tn a m e ,"w a sr e m o v e d . " e l s e : p r i n tn a m e ,"w a sn o tf o u n d . " e l i fm e n u _ c h o i c e= =4 : p r i n t" L o o k u pW o r d " n a m e=r a w _ i n p u t ( " W o r d :" ) i fn a m ei nw o r d s : p r i n t" T h ed e f i n i t i o no f" ,n a m e ,"i s :" ,w o r d s [ n a m e ] e l s e : p r i n tn a m e ," N od e f i n i t i o nf o r" ,n a m e ,"w a sf o u n d . " e l i fm e n u _ c h o i c e! =5 : p r i n t _ m e n u ( )

Andhereismyoutput:
1 .P r i n tD i c t i o n a r y 2 .A d dd e f i n i t i o n 3 .R e m o v ew o r d 4 .L o o k u pw o r d 5 .Q u i t T y p ei nan u m b e r( 1 5 ) :2 A d dd e f i n i t i o n W o r d :P y t h o n D e f i n i t i o n :As n a k e ,ap r o g r a m m i n gl a n g u a g e ,a n daB r i t i s hc o m e d y . T y p ei nan u m b e r( 1 5 ) :2 A d dd e f i n i t i o n W o r d :D i c t i o n a r y
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 66/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

D e f i n i t i o n :Ab o o kw h e r ew o r d sa r ed e f i n e d . T y p ei nan u m b e r( 1 5 ) :1 D e f i n i t i o n s : P y t h o n :As n a k e ,ap r o g r a m m i n gl a n g u a g e ,a n daB r i t i s hc o m e d y . D i c t i o n a r y :Ab o o kw h e r ew o r d sa r ed e f i n e d . T y p ei nan u m b e r( 1 5 ) :4 L o o k u pW o r d W o r d :P y t h o n T h ed e f i n i t i o no fP y t h o ni s :As n a k e ,ap r o g r a m m i n gl a n g u a g e ,a n daB r i t i s hc o m e d y . T y p ei nan u m b e r( 1 5 ) :3 R e m o v eW o r d W o r d :D i c t i o n a r y D i c t i o n a r yw a sr e m o v e d . T y p ei nan u m b e r( 1 5 ) :1 D e f i n i t i o n s : P y t h o n :As n a k e ,ap r o g r a m m i n gl a n g u a g e ,a n daB r i t i s hc o m e d y . T y p ei nan u m b e r( 1 5 ) :5

Thisprogramissimilartothenamelistfromtheearlierchapteronlists(notethatlistsuseindexesanddictionariesdon't).Here'showtheprogramworks: Firstthefunction p r i n t _ m e n u isdefined. p r i n t _ m e n u justprintsamenuthatislaterusedtwiceintheprogram. Nextcomesthefunnylookingline w o r d s={ } .AllthatlinedoesistellPythonthat w o r d s isadictionary. Thenextfewlinesjustmakethemenuwork.


f o rxi nw o r d s . k e y s ( ) : p r i n tx ," :" ,w o r d s [ x ]

Thisgoesthroughthedictionaryandprintsalltheinformation.Thefunction w o r d s . k e y s ( ) returnsalistthatisthenusedbythe f o r loop.Thelistreturned by k e y s ( ) isnotinanyparticularordersoifyouwantitinalphabeticorderitmustbesorted.Similartoliststhestatement w o r d s [ x ] isusedtoaccessa specificmemberofthedictionary.Ofcourseinthiscase x isastring. Nexttheline w o r d s [ n a m e ]=m e a n s addsawordanddefinitiontothedictionary.If n a m e isalreadyinthedictionary m e a n s replaceswhateverwastherebefore.
i fn a m ei nw o r d s : d e lw o r d s [ n a m e ]

Seeifnameisinwordsandremoveitifitis.Theexpression n a m ei nw o r d s returnstrueif n a m e isakeyin w o r d s butotherwisereturnsfalse.Theline d e l


w o r d s [ n a m e ] removesthekey n a m e andthevalueassociatedwiththatkey.

i fn a m ei nw o r d s : p r i n t" T h ed e f i n i t i o no f" ,n a m e ,"i s :" ,w o r d s [ n a m e ]


en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 67/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

Checktoseeifwordshasacertainkeyandifitdoesprintsoutthedefinitionassociatedwithit. Lastlyifthemenuchoiceisinvaliditreprintsthemenuforyourviewingpleasure. Arecap:Dictionarieshavekeysandvalues.Keyscanbestringsornumbers.Keyspointtovalues.Valuescanbeanytypeofvariable(includinglistsoreven dictionaries(thosedictionariesorlistsofcoursecancontaindictionariesorliststhemselves(scaryright?:))).Hereisanexampleofusingalistinadictionary:


m a x _ p o i n t s=[ 2 5 ,2 5 ,5 0 ,2 5 ,1 0 0 ] a s s i g n m e n t s=[ ' h wc h1 ' ,' h wc h2 ' ,' q u i z ' ,' h wc h3 ' ,' t e s t ' ] s t u d e n t s={ ' # M a x ' :m a x _ p o i n t s } d e fp r i n t _ m e n u ( ) : p r i n t" 1 .A d ds t u d e n t " p r i n t" 2 .R e m o v es t u d e n t " p r i n t" 3 .P r i n tg r a d e s " p r i n t" 4 .R e c o r dg r a d e " p r i n t" 5 .P r i n tM e n u " p r i n t" 6 .E x i t " d e fp r i n t _ a l l _ g r a d e s ( ) : p r i n t' \ t ' , f o rii nr a n g e ( l e n ( a s s i g n m e n t s ) ) : p r i n ta s s i g n m e n t s [ i ] ,' \ t ' , p r i n t k e y s=s t u d e n t s . k e y s ( ) k e y s . s o r t ( ) f o rxi nk e y s : p r i n tx ,' \ t ' , g r a d e s=s t u d e n t s [ x ] p r i n t _ g r a d e s ( g r a d e s ) d e fp r i n t _ g r a d e s ( g r a d e s ) : f o rii nr a n g e ( l e n ( g r a d e s ) ) : p r i n tg r a d e s [ i ] ,' \ t ' ,' \ t ' , p r i n t p r i n t _ m e n u ( ) m e n u _ c h o i c e=0 w h i l em e n u _ c h o i c e! =6 : p r i n t m e n u _ c h o i c e=i n p u t ( " M e n uC h o i c e( 1 6 ) :" ) i fm e n u _ c h o i c e= =1 : n a m e=r a w _ i n p u t ( " S t u d e n tt oa d d :" ) s t u d e n t s [ n a m e ]=[ 0 ]*l e n ( m a x _ p o i n t s ) e l i fm e n u _ c h o i c e= =2 : n a m e=r a w _ i n p u t ( " S t u d e n tt or e m o v e :" ) i fn a m ei ns t u d e n t s : d e ls t u d e n t s [ n a m e ] e l s e : p r i n t" S t u d e n t : " ,n a m e ," n o tf o u n d " e l i fm e n u _ c h o i c e= =3 : p r i n t _ a l l _ g r a d e s ( ) e l i fm e n u _ c h o i c e= =4 : p r i n t" R e c o r dG r a d e " n a m e=r a w _ i n p u t ( " S t u d e n t :" )
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 68/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

i fn a m ei ns t u d e n t s : g r a d e s=s t u d e n t s [ n a m e ] p r i n t" T y p ei nt h en u m b e ro ft h eg r a d et or e c o r d " p r i n t" T y p ea0( z e r o )t oe x i t " f o rii nr a n g e ( l e n ( a s s i g n m e n t s ) ) : p r i n ti+1 ,a s s i g n m e n t s [ i ] ,' \ t ' , p r i n t p r i n t _ g r a d e s ( g r a d e s ) w h i c h=1 2 3 4 w h i l ew h i c h! =1 : w h i c h=i n p u t ( " C h a n g ew h i c hG r a d e :" ) w h i c h=w h i c h-1 i f0< =w h i c h<l e n ( g r a d e s ) : g r a d e=i n p u t ( " G r a d e :" ) g r a d e s [ w h i c h ]=g r a d e e l i fw h i c h! =1 : p r i n t" I n v a l i dG r a d eN u m b e r " e l s e : p r i n t" S t u d e n tn o tf o u n d " e l i fm e n u _ c h o i c e! =6 : p r i n t _ m e n u ( )

andhereisasampleoutput:
1 .A d ds t u d e n t 2 .R e m o v es t u d e n t 3 .P r i n tg r a d e s 4 .R e c o r dg r a d e 5 .P r i n tM e n u 6 .E x i t M e n uC h o i c e( 1 6 ) :3 h wc h1 h wc h2 # M a x 2 5 2 5 M e n uC h o i c e( 1 6 ) :5 1 .A d ds t u d e n t 2 .R e m o v es t u d e n t 3 .P r i n tg r a d e s 4 .R e c o r dg r a d e 5 .P r i n tM e n u 6 .E x i t M e n uC h o i c e( 1 6 ) :1 S t u d e n tt oa d d :B i l l M e n uC h o i c e( 1 6 ) :4 R e c o r dG r a d e S t u d e n t :B i l l T y p ei nt h en u m b e ro ft h eg r a d et or e c o r d T y p ea0( z e r o )t oe x i t
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 69/99

q u i z 5 0

h wc h3 2 5

t e s t 1 0 0

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

1 h wc h1 2 h wc h2 0 0 C h a n g ew h i c hG r a d e :1 G r a d e :2 5 C h a n g ew h i c hG r a d e :2 G r a d e :2 4 C h a n g ew h i c hG r a d e :3 G r a d e :4 5 C h a n g ew h i c hG r a d e :4 G r a d e :2 3 C h a n g ew h i c hG r a d e :5 G r a d e :9 5 C h a n g ew h i c hG r a d e :0 M e n uC h o i c e( 1 6 ) :3 h wc h1 h wc h2 # M a x 2 5 2 5 B i l l 2 5 2 4 M e n uC h o i c e( 1 6 ) :6

3 q u i z 0

4 h wc h3 0

5 t e s t 0

q u i z 5 0 4 5

h wc h3 2 5 2 3

t e s t 1 0 0 9 5

Hereshowtheprogramworks.Basicallythevariable s t u d e n t s isadictionarywiththekeysbeingthenameofthestudentsandthevaluesbeingtheirgrades. Thefirsttwolinesjustcreatetwolists.Thenextline s t u d e n t s={ ' # M a x ' :m a x _ p o i n t s } createsanewdictionarywiththekey{# M a x }andthevalueissettobe [ 2 5 ,2 5 , 5 0 ,2 5 ,1 0 0 ] ,sincethatswhat m a x _ p o i n t s waswhentheassignmentismade(Iusethekey # M a x since # issortedaheadofanyalphabeticcharacters).Next p r i n t _ m e n u isdefined.Nextthe p r i n t _ a l l _ g r a d e s functionisdefinedinthelines:
d e fp r i n t _ a l l _ g r a d e s ( ) : p r i n t' \ t ' , f o rii nr a n g e ( l e n ( a s s i g n m e n t s ) ) : p r i n ta s s i g n m e n t s [ i ] ,' \ t ' , p r i n t k e y s=s t u d e n t s . k e y s ( ) k e y s . s o r t ( ) f o rxi nk e y s : p r i n tx ,' \ t ' , g r a d e s=s t u d e n t s [ x ] p r i n t _ g r a d e s ( g r a d e s )

Noticehowfirstthekeysaregottenoutofthe s t u d e n t s dictionarywiththe k e y s functionintheline k e y s=s t u d e n t s . k e y s ( ) . k e y s isalistsoallthefunctionsforlists canbeusedonit.Nextthekeysaresortedintheline k e y s . s o r t ( ) sinceitisalist. f o r isusedtogothroughallthekeys.Thegradesarestoredasalistinside thedictionarysotheassignment g r a d e s=s t u d e n t s [ x ] gives g r a d e s thelistthatisstoredatthekey x .Thefunction p r i n t _ g r a d e s justprintsalistandisdefinedafew lineslater. Thelaterlinesoftheprogramimplementthevariousoptionsofthemenu.Theline s t u d e n t s [ n a m e ]=[ 0 ]*l e n ( m a x _ p o i n t s ) addsastudenttothekeyoftheirname. Thenotation [ 0 ]*l e n ( m a x _ p o i n t s ) justcreatesalistof0'sthatisthesamelengthasthe m a x _ p o i n t s list.

Theremovestudententryjustdeletesastudentsimilartothetelephonebookexample.Therecordgradeschoiceisalittlemorecomplex.Thegradesare en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version

70/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

Theremovestudententryjustdeletesastudentsimilartothetelephonebookexample.Therecordgradeschoiceisalittlemorecomplex.Thegradesare retrievedintheline g r a d e s=s t u d e n t s [ n a m e ] getsareferencetothegradesofthestudent n a m e .Agradeisthenrecordedintheline g r a d e s [ w h i c h ]=g r a d e .Youmay noticethat g r a d e s isneverputbackintothestudentsdictionary(asinno s t u d e n t s [ n a m e ]=g r a d e s ).Thereasonforthemissingstatementisthat g r a d e s isactually anothernamefor s t u d e n t s [ n a m e ] andsochanging g r a d e s changes s t u d e n t [ n a m e ] . Dictionariesprovideaeasywaytolinkkeystovalues.Thiscanbeusedtoeasilykeeptrackofdatathatisattachedtovariouskeys.

UsingModules
Here'sthischapter'stypingexercise(nameitcal.py). i m p o r t actuallylooksforafilenamedcalendar.pyandreadsitin.Ifthefileisnamedcalendar.pyandit seesa"importcalendar"ittriestoreadinitselfwhichworkspoorlyatbest.)):
i m p o r tc a l e n d a r y e a r=i n p u t ( " T y p ei nt h ey e a rn u m b e r :" ) c a l e n d a r . p r c a l ( y e a r )

AndhereispartoftheoutputIgot:
T y p ei nt h ey e a rn u m b e r :2 0 0 1 2 0 0 1 J a n u a r y M oT uW eT hF rS aS u 1 2 3 4 5 6 7 8 91 01 11 21 31 4 1 51 61 71 81 92 02 1 2 22 32 42 52 62 72 8 2 93 03 1 F e b r u a r y M oT uW eT hF rS aS u 1 2 3 4 5 6 7 8 91 01 1 1 21 31 41 51 61 71 8 1 92 02 12 22 32 42 5 2 62 72 8 M a r c h M oT uW eT hF rS aS u 1 2 3 4 5 6 7 8 91 01 1 1 21 31 41 51 61 71 8 1 92 02 12 22 32 42 5 2 62 72 82 93 03 1

(Iskippedsomeoftheoutput,butIthinkyougettheidea.)Sowhatdoestheprogramdo?Thefirstline i m p o r tc a l e n d a r usesanewcommand i m p o r t .The command i m p o r t loadsamodule(inthiscasethe c a l e n d a r module).Toseethecommandsavailableinthestandardmoduleseitherlookinthelibraryreference forpython(ifyoudownloadedit)orgotohttp://docs.python.org/library/.Ifyoulookatthedocumentationforthecalendarmodule,itlistsafunctioncalled p r c a l thatprintsacalendarforayear.Theline c a l e n d a r . p r c a l ( y e a r ) usesthisfunction.Insummarytouseamodule i m p o r t itandthenuse m o d u l e _ n a m e . f u n c t i o n for functionsinthemodule.Anotherwaytowritetheprogramis:
f r o mc a l e n d a ri m p o r tp r c a l y e a r=i n p u t ( " T y p ei nt h ey e a rn u m b e r :" ) p r c a l ( y e a r )

en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version

Thisversionimportsaspecificfunctionfromamodule.HereisanotherprogramthatusesthePythonLibrary(nameitsomethinglikeclock.py)(pressCtrland71/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

Thisversionimportsaspecificfunctionfromamodule.HereisanotherprogramthatusesthePythonLibrary(nameitsomethinglikeclock.py)(pressCtrland the'c'keyatthesametimetoterminatetheprogram):
f r o mt i m ei m p o r tt i m e ,c t i m e p r e v _ t i m e=" " w h i l eT r u e : t h e _ t i m e=c t i m e ( t i m e ( ) ) i fp r e v _ t i m e! =t h e _ t i m e : p r i n t" T h et i m ei s : " ,c t i m e ( t i m e ( ) ) p r e v _ t i m e=t h e _ t i m e

Withsomeoutputbeing:
T h et i m ei s :S u nA u g2 01 3 : 4 0 : 0 42 0 0 0 T h et i m ei s :S u nA u g2 01 3 : 4 0 : 0 52 0 0 0 T h et i m ei s :S u nA u g2 01 3 : 4 0 : 0 62 0 0 0 T h et i m ei s :S u nA u g2 01 3 : 4 0 : 0 72 0 0 0 T r a c e b a c k( i n n e r m o s tl a s t ) : F i l e" c l o c k . p y " ,l i n e5 ,i n? t h e _ t i m e=c t i m e ( t i m e ( ) ) K e y b o a r d I n t e r r u p t

TheoutputisinfiniteofcoursesoIcanceledit(ortheoutputatleastcontinuesuntilCtrl+Cispressed).Theprogramjustdoesainfiniteloop(T r u e isalways true,so w h i l eT r u e : goesforever)andeachtimecheckstoseeifthetimehaschangedandprintsitifithas.Noticehowmultiplenamesaftertheimport statementareusedintheline f r o mt i m ei m p o r tt i m e ,c t i m e . ThePythonLibrarycontainsmanyusefulfunctions.ThesefunctionsgiveyourprogramsmoreabilitiesandmanyofthemcansimplifyprogramminginPython.

Exercises
RewritetheHigh_low.pyprogramfromsectionDecisionstousearandomintegerbetween0and99insteadofthehardcoded78.UsethePython documentationtofindanappropriatemoduleandfunctiontodothis. Solution RewritetheHigh_low.pyprogramfromsectionDecisionstouseanrandomintegerbetween0and99insteadofthehardcoded78.UsethePython documentationtofindanappropriatemoduleandfunctiontodothis.

f r o mr a n d o mi m p o r tr a n d i n t n u m b e r=r a n d i n t ( 0 ,9 9 )
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 72/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

g u e s s=1 w h i l eg u e s s! =n u m b e r : g u e s s=i n p u t( " G u e s san u m b e r :" ) i fg u e s s>n u m b e r : p r i n t" T o oh i g h " e l i fg u e s s<n u m b e r : p r i n t" T o ol o w " p r i n t" J u s tr i g h t "

MoreonLists
Wehavealreadyseenlistsandhowtheycanbeused.NowthatyouhavesomemorebackgroundIwillgointomoredetailaboutlists.Firstwewilllookat morewaystogetattheelementsinalistandthenwewilltalkaboutcopyingthem. Herearesomeexamplesofusingindexingtoaccessasingleelementofalist:
> > >s o m e _ n u m b e r s=[ ' z e r o ' ,' o n e ' ,' t w o ' ,' t h r e e ' ,' f o u r ' ,' f i v e ' ] > > >s o m e _ n u m b e r s [ 0 ] ' z e r o ' > > >s o m e _ n u m b e r s [ 4 ] ' f o u r ' > > >s o m e _ n u m b e r s [ 5 ] ' f i v e '

Allthoseexamplesshouldlookfamiliartoyou.Ifyouwantthefirstiteminthelistjustlookatindex0.Theseconditemisindex1andsoonthroughthelist. Howeverwhatifyouwantthelastiteminthelist?Onewaycouldbetousethe l e n ( ) functionlike s o m e _ n u m b e r s [ l e n ( s o m e _ n u m b e r s )-1 ] .Thiswayworkssincethe l e n ( ) functionalwaysreturnsthelastindexplusone.Thesecondfromthelastwouldthenbe s o m e _ n u m b e r s [ l e n ( s o m e _ n u m b e r s )-2 ] .Thereisaneasierwaytodothis. InPythonthelastitemisalwaysindex1.Thesecondtothelastisindex2andsoon.Herearesomemoreexamples:


> > >s o m e _ n u m b e r s [ l e n ( s o m e _ n u m b e r s )-1 ] ' f i v e ' > > >s o m e _ n u m b e r s [ l e n ( s o m e _ n u m b e r s )-2 ] ' f o u r ' > > >s o m e _ n u m b e r s [ 1 ] ' f i v e ' > > >s o m e _ n u m b e r s [ 2 ] ' f o u r ' > > >s o m e _ n u m b e r s [ 6 ] ' z e r o '

Thusanyiteminthelistcanbeindexedintwoways:fromthefrontandfromtheback.
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 73/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

Anotherusefulwaytogetintopartsoflistsisusingslicing.Hereisanotherexampletogiveyouanideawhattheycanbeusedfor:
> > >t h i n g s=[ 0 ,' F r e d ' ,2 ,' S . P . A . M . ' ,' S t o c k i n g ' ,4 2 ," J a c k " ," J i l l " ] > > >t h i n g s [ 0 ] 0 > > >t h i n g s [ 7 ] ' J i l l ' > > >t h i n g s [ 0 : 8 ] [ 0 ,' F r e d ' ,2 ,' S . P . A . M . ' ,' S t o c k i n g ' ,4 2 ,' J a c k ' ,' J i l l ' ] > > >t h i n g s [ 2 : 4 ] [ 2 ,' S . P . A . M . ' ] > > >t h i n g s [ 4 : 7 ] [ ' S t o c k i n g ' ,4 2 ,' J a c k ' ] > > >t h i n g s [ 1 : 5 ] [ ' F r e d ' ,2 ,' S . P . A . M . ' ,' S t o c k i n g ' ]

Slicingisusedtoreturnpartofalist.Theslicingoperatorisintheform t h i n g s [ f i r s t _ i n d e x : l a s t _ i n d e x ] .Slicingcutsthelistbeforethe f i r s t _ i n d e x andbeforethe l a s t _ i n d e x andreturnsthepartsinbetween.Youcanusebothtypesofindexing:


> > >t h i n g s [ 4 : 2 ] [ ' S t o c k i n g ' ,4 2 ] > > >t h i n g s [ 4 ] ' S t o c k i n g ' > > >t h i n g s [ 4 : 6 ] [ ' S t o c k i n g ' ,4 2 ]

Anothertrickwithslicingistheunspecifiedindex.Ifthefirstindexisnotspecifiedthebeginningofthelistisassumed.Ifthelastindexisnotspecifiedthe wholerestofthelistisassumed.Herearesomeexamples:
> > >t h i n g s [ : 2 ] [ 0 ,' F r e d ' ] > > >t h i n g s [ 2 : ] [ ' J a c k ' ,' J i l l ' ] > > >t h i n g s [ : 3 ] [ 0 ,' F r e d ' ,2 ] > > >t h i n g s [ : 5 ] [ 0 ,' F r e d ' ,2 ]

Hereisa(HTMLinspired)programexample(copyandpasteinthepoemdefinitionifyouwant):
p o e m=[ " < B > " ," J a c k " ," a n d " ," J i l l " ," < / B > " ," w e n t " ," u p " ," t h e " , " h i l l " ," t o " ," < B > " ," f e t c h " ," a " ," p a i l " ," o f " ," < / B > " , " w a t e r . " ," J a c k " ," f e l l " ," < B > " ," d o w n " ," a n d " ," b r o k e " , " < / B > " ," h i s " ," c r o w n " ," a n d " ," < B > " ," J i l l " ," c a m e " ,
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 74/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

" < / B > " ," t u m b l i n g " ," a f t e r " ] d e fg e t _ b o l d s ( t e x t ) : t r u e=1 f a l s e=0 # #i s _ b o l dt e l l sw h e t h e ro rn o tt h ew ea r ec u r r e n t l yl o o k i n ga t # #ab o l ds e c t i o no ft e x t . i s _ b o l d=f a l s e # #s t a r t _ b l o c ki st h ei n d e xo ft h es t a r to fe i t h e ra nu n b o l d e d # #s e g m e n to ft e x to rab o l d e ds e g m e n t . s t a r t _ b l o c k=0 f o ri n d e xi nr a n g e ( l e n ( t e x t ) ) : # #H a n d l eas t a r t i n go fb o l dt e x t i ft e x t [ i n d e x ]= =" < B > " : i fi s _ b o l d : p r i n t" E r r o r :E x t r aB o l d " # #p r i n t" N o tB o l d : " ,t e x t [ s t a r t _ b l o c k : i n d e x ] i s _ b o l d=t r u e s t a r t _ b l o c k=i n d e x+1 # #H a n d l ee n do fb o l dt e x t # #R e m e m b e rt h a tt h el a s tn u m b e ri nas l i c ei st h ei n d e x # #a f t e rt h el a s ti n d e xu s e d . i ft e x t [ i n d e x ]= =" < / B > " : i fn o ti s _ b o l d : p r i n t" E r r o r :E x t r aC l o s eB o l d " p r i n t" B o l d[ " ,s t a r t _ b l o c k ," : " ,i n d e x ," ] " ,t e x t [ s t a r t _ b l o c k : i n d e x ] i s _ b o l d=f a l s e s t a r t _ b l o c k=i n d e x+1 g e t _ b o l d s ( p o e m )

withtheoutputbeing:
B o l d[1:4][ ' J a c k ' ,' a n d ' ,' J i l l ' ] B o l d[1 1:1 5][ ' f e t c h ' ,' a ' ,' p a i l ' ,' o f ' ] B o l d[2 0:2 3][ ' d o w n ' ,' a n d ' ,' b r o k e ' ] B o l d[2 8:3 0][ ' J i l l ' ,' c a m e ' ]

The g e t _ b o l d ( ) functiontakesinalistthatisbrokenintowordsandtokens.Thetokensthatitlooksforare < B > whichstartstheboldtextand < / B > whichends boldtext.Thefunction g e t _ b o l d ( ) goesthroughandsearchesforthestartandendtokens. Thenextfeatureoflistsiscopyingthem.Ifyoutrysomethingsimplelike:
> > >a=[ 1 ,2 ,3 ] > > >b=a > > >p r i n tb [ 1 ,2 ,3 ] > > >b [ 1 ]=1 0 > > >p r i n tb
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 75/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

[ 1 ,1 0 ,3 ] > > >p r i n ta [ 1 ,1 0 ,3 ]

Thisprobablylookssurprisingsinceamodificationto b resultedin a beingchangedaswell.Whathappenedisthatthestatement b=a makes b a referenceto a .Thismeansthat b canbethoughtofasanothernamefor a .Henceanymodificationto b changes a aswell.Howeversomeassignmentsdon'tcreatetwo namesforonelist:
> > >a=[ 1 ,2 ,3 ] > > >b=a*2 > > >p r i n ta [ 1 ,2 ,3 ] > > >p r i n tb [ 1 ,2 ,3 ,1 ,2 ,3 ] > > >a [ 1 ]=1 0 > > >p r i n ta [ 1 ,1 0 ,3 ] > > >p r i n tb [ 1 ,2 ,3 ,1 ,2 ,3 ]

Inthiscase b isnotareferenceto a sincetheexpression a*2 createsanewlist.Thenthestatement b=a*2 gives b areferenceto a*2 ratherthana referenceto a .Allassignmentoperationscreateareference.Whenyoupassalistasanargumenttoafunctionyoucreateareferenceaswell.Mostofthe timeyoudon'thavetoworryaboutcreatingreferencesratherthancopies.Howeverwhenyouneedtomakemodificationstoonelistwithoutchanginganother nameofthelistyouhavetomakesurethatyouhaveactuallycreatedacopy. Thereareseveralwaystomakeacopyofalist.Thesimplestthatworksmostofthetimeisthesliceoperatorsinceitalwaysmakesanewlistevenifitisa sliceofawholelist:
> > >a=[ 1 ,2 ,3 ] > > >b=a [ : ] > > >b [ 1 ]=1 0 > > >p r i n ta [ 1 ,2 ,3 ] > > >p r i n tb [ 1 ,1 0 ,3 ]

Takingtheslice [ : ] createsanewcopyofthelist.Howeveritonlycopiestheouterlist.Anysublistinsideisstillareferencestothesublistintheoriginallist. Therefore,whenthelistcontainslists,theinnerlistshavetobecopiedaswell.YoucoulddothatmanuallybutPythonalreadycontainsamoduletodoit.You usethe d e e p c o p y functionofthe c o p y module:


> > >i m p o r tc o p y > > >a=[ [ 1 ,2 ,3 ] ,[ 4 ,5 ,6 ] ] > > >b=a [ : ]
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 76/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

> > >c=c o p y . d e e p c o p y ( a ) > > >b [ 0 ] [ 1 ]=1 0 > > >c [ 1 ] [ 1 ]=1 2 > > >p r i n ta [ [ 1 ,1 0 ,3 ] ,[ 4 ,5 ,6 ] ] > > >p r i n tb [ [ 1 ,1 0 ,3 ] ,[ 4 ,5 ,6 ] ] > > >p r i n tc [ [ 1 ,2 ,3 ] ,[ 4 ,1 2 ,6 ] ]

Firstofallnoticethat a isalistoflists.Thennoticethatwhen b [ 0 ] [ 1 ]=1 0 isrunboth a and b arechanged,but c isnot.Thishappensbecausetheinnerarrays arestillreferenceswhenthesliceoperatorisused.Howeverwith d e e p c o p y c wasfullycopied. So,shouldIworryaboutreferenceseverytimeIuseafunctionor = ?Thegoodnewsisthatyouonlyhavetoworryaboutreferenceswhenusingdictionaries andlists.Numbersandstringscreatereferenceswhenassignedbuteveryoperationonnumbersandstringsthatmodifiesthemcreatesanewcopysoyoucan nevermodifythemunexpectedly.Youdohavetothinkaboutreferenceswhenyouaremodifyingalistoradictionary. Bynowyouareprobablywonderingwhyarereferencesusedatall?Thebasicreasonisspeed.Itismuchfastertomakeareferencetoathousandelement listthantocopyalltheelements.Theotherreasonisthatitallowsyoutohaveafunctiontomodifytheinputedlistordictionary.Justrememberabout referencesifyoueverhavesomeweirdproblemwithdatabeingchangedwhenitshouldn'tbe.

RevengeoftheStrings
Andnowpresentingacooltrickthatcanbedonewithstrings:
d e fs h o u t ( s t r i n g ) : f o rc h a r a c t e ri ns t r i n g : p r i n t" G i m m ea"+c h a r a c t e r p r i n t" ' "+c h a r a c t e r+" ' " s h o u t ( " L o s e " ) d e fm i d d l e ( s t r i n g ) : p r i n t" T h em i d d l ec h a r a c t e ri s : " ,s t r i n g [ l e n ( s t r i n g )/2 ] m i d d l e ( " a b c d e f g " ) m i d d l e ( " T h eP y t h o nP r o g r a m m i n gL a n g u a g e " ) m i d d l e ( " A t l a n t a " )

Andtheoutputis:
G i m m eaL ' L ' G i m m eao ' o ' G i m m eas ' s '
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 77/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

G i m m eae ' e ' T h em i d d l ec h a r a c t e ri s :d T h em i d d l ec h a r a c t e ri s :r T h em i d d l ec h a r a c t e ri s :a

Whattheseprogramsdemonstrateisthatstringsaresimilartolistsinseveralways.The s h o u t ( ) functionshowsthat f o r loopscanbeusedwithstringsjustas theycanbeusedwithlists.The m i d d l e procedureshowsthatthatstringscanalsousethe l e n ( ) functionandarrayindexesandslices.Mostlistfeaturesworkon stringsaswell. Thenextfeaturedemonstratessomestringspecificfeatures:


d e ft o _ u p p e r ( s t r i n g ) : # #C o n v e r t sas t r i n gt ou p p e rc a s e u p p e r _ c a s e=" " f o rc h a r a c t e ri ns t r i n g : i f' a '< =c h a r a c t e r< =' z ' : l o c a t i o n=o r d ( c h a r a c t e r )-o r d ( ' a ' ) n e w _ a s c i i=l o c a t i o n+o r d ( ' A ' ) c h a r a c t e r=c h r ( n e w _ a s c i i ) u p p e r _ c a s e=u p p e r _ c a s e+c h a r a c t e r r e t u r nu p p e r _ c a s e p r i n tt o _ u p p e r ( " T h i si sT e x t " )

withtheoutputbeing:
T H I SI ST E X T

Thisworksbecausethecomputerrepresentsthecharactersofastringasnumbersfrom0to255.Pythonhasafunctioncalled o r d ( ) (shortforordinal)that returnsacharacterasanumber.Thereisalsoacorrespondingfunctioncalled c h r ( ) thatconvertsanumberintoacharacter.Withthisinmindtheprogram shouldstarttobeclear.Thefirstdetailistheline: i f' a '< =c h a r a c t e r< =' z ' : whichcheckstoseeifaletterislowercase.Ifitisthenthenextlinesareused. Firstitisconvertedintoalocationsothata=0,b=1,c=2andsoonwiththeline: l o c a t i o n=o r d ( c h a r a c t e r )-o r d ( ' a ' ) .Nextthenewvalueisfoundwith n e w _ a s c i i=l o c a t i o n+o r d ( ' A ' ) .Thisvalueisconvertedbacktoacharacterthatisnowuppercase. Nowforsomeinteractivetypingexercise:
> > >#I n t e g e rt oS t r i n g > > >2 2 > > >r e p r ( 2 ) ' 2 ' > > >1 2 3 1 2 3 > > >r e p r ( 1 2 3 )
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 78/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

' 1 2 3 ' > > >` 1 2 3 ` ' 1 2 3 ' > > >#S t r i n gt oI n t e g e r > > >" 2 3 " ' 2 3 ' > > >i n t ( " 2 3 " ) 2 3 > > >" 2 3 "*2 ' 2 3 2 3 ' > > >i n t ( " 2 3 " )*2 4 6 > > >#F l o a tt oS t r i n g > > >1 . 2 3 1 . 2 3 > > >r e p r ( 1 . 2 3 ) ' 1 . 2 3 ' > > >#F l o a tt oI n t e g e r > > >1 . 2 3 1 . 2 3 > > >i n t ( 1 . 2 3 ) 1 > > >i n t ( 1 . 2 3 ) 1 > > >#S t r i n gt oF l o a t > > >f l o a t ( " 1 . 2 3 " ) 1 . 2 3 > > >" 1 . 2 3 " ' 1 . 2 3 ' > > >f l o a t ( " 1 2 3 " ) 1 2 3 . 0 > > >` f l o a t ( " 1 . 2 3 " ) ` ' 1 . 2 3 '

Ifyouhaven'tguessedalreadythefunction r e p r ( ) canconvertaintegertoastringandthefunction i n t ( ) canconvertastringtoaninteger.Thefunction f l o a t ( ) canconvertastringtoafloat.The r e p r ( ) functionreturnsaprintablerepresentationofsomething. ` . . . ` convertsalmosteverythingintoastring,too.Hereare someexamplesofthis:


> > >r e p r ( 1 ) ' 1 ' > > >r e p r ( 2 3 4 . 1 4 ) ' 2 3 4 . 1 4 ' > > >r e p r ( [ 4 ,4 2 ,1 0 ] ) ' [ 4 ,4 2 ,1 0 ] ' > > >` [ 4 ,4 2 ,1 0 ] ` ' [ 4 ,4 2 ,1 0 ] '

en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version

79/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

The i n t ( ) functiontriestoconvertastring(orafloat)intoainteger.Thereisalsoasimilarfunctioncalled f l o a t ( ) thatwillconvertaintegerorastringintoa float.AnotherfunctionthatPythonhasisthe e v a l ( ) function.The e v a l ( ) functiontakesastringandreturnsdataofthetypethatpythonthinksitfound.For example:


> > >v=e v a l ( ' 1 2 3 ' ) > > >p r i n tv ,t y p e ( v ) 1 2 3< t y p e' i n t ' > > > >v=e v a l ( ' 6 4 5 . 1 2 3 ' ) > > >p r i n tv ,t y p e ( v ) 6 4 5 . 1 2 3< t y p e' f l o a t ' > > > >v=e v a l ( ' [ 1 ,2 ,3 ] ' ) > > >p r i n tv ,t y p e ( v ) [ 1 ,2 ,3 ]< t y p e' l i s t ' >

Ifyouusethe e v a l ( ) functionyoushouldcheckthatitreturnsthetypethatyouexpect. Oneusefulstringfunctionisthe s p l i t ( ) method.Here'sanexample:


> > >" T h i si sab u n c ho fw o r d s " . s p l i t ( ) [ ' T h i s ' ,' i s ' ,' a ' ,' b u n c h ' ,' o f ' ,' w o r d s ' ] > > >t e x t=" F i r s tb a t c h ,s e c o n db a t c h ,t h i r d ,f o u r t h " > > >t e x t . s p l i t ( " , " ) [ ' F i r s tb a t c h ' ,'s e c o n db a t c h ' ,'t h i r d ' ,'f o u r t h ' ]

Noticehow s p l i t ( ) convertsastringintoalistofstrings.Thestringissplitbywhitespacebydefaultorbytheoptionalargument(inthiscaseacomma).You canalsoaddanotherargumentthattells s p l i t ( ) howmanytimestheseparatorwillbeusedtosplitthetext.Forexample:


> > >l i s t=t e x t . s p l i t ( " , " ) > > >l e n ( l i s t ) 4 > > >l i s t [ 1 ] 'f o u r t h ' > > >l i s t=t e x t . s p l i t ( " , " ,2 ) > > >l e n ( l i s t ) 3 > > >l i s t [ 1 ] 't h i r d ,f o u r t h '

Slicingstrings(andlists)
Stringscanbecutintopiecesinthesamewayasitwasshownforlistsinthepreviouschapterbyusingthe slicing"operator" [ : ] .Theslicingoperator worksinthesamewayasbefore:text[first_index:last_index](inveryrarecasestherecanbeanothercolonandathirdargument,asintheexampleshown below).
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 80/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

Inordernottogetconfusedbytheindexnumbers,itiseasiesttoseethemas clippingplaces,possibilitiestocutastringintoparts.Hereisanexample,which showstheclippingplaces(inyellow)andtheirindexnumbers(redandblue)forasimpletextstring: 0 text= " [: S 1 T 2 R ... I 2 N 1 G :] "

Notethattheredindexesarecountedfromthebeginningofthestringandtheblueonesfromtheendofthestringbackwards.(Notethatthereisnoblue0, whichcouldseemtobelogicalattheendofthestring.Because 0= =0 ,(0means"beginningofthestring"aswell.)Nowwearereadytousetheindexesfor slicingoperations: text[1:4] text[:5] text[:1] text[4:] text[2] text[:] text[::1] "TRI" "STRIN" "STRIN" "RING" "R" "STRING" "GNIRTS"

t e x t [ 1 : 4 ] givesusallofthe t e x t stringbetweenclippingplaces1and4," T R I ".Ifyouomitoneofthe[first_index:last_index]arguments,yougetthebeginningor

endofthestringasdefault: t e x t [ : 5 ] gives" S T R I N ".Forboth f i r s t _ i n d e x and l a s t _ i n d e x wecanuseboththeredandthebluenumberingschema: t e x t [ : 1 ] givesthe sameas t e x t [ : 5 ] ,becausetheindex1isatthesameplaceas5inthiscase.Ifwedonotuseanargumentcontainingacolon,thenumberistreatedina differentway: t e x t [ 2 ] givesusonecharacterfollowingthesecondclippingpoint," R ".Thespecialslicingoperation t e x t [ : ] means"fromthebeginningtotheend" andproducesacopyoftheentirestring(orlist,asshowninthepreviouschapter). Lastbutnotleast,theslicingoperationcanhaveasecondcolonandathirdargument,whichisinterpretedasthe"stepsize": t e x t [ : : 1 ] is t e x t frombeginning totheend,withastepsizeof1.1means"everycharacter,butintheotherdirection"." S T R I N G "backwardsis" G N I R T S "(testasteplengthof2,ifyouhavenot gotthepointhere). Alltheseslicingoperationsworkwithlistsaswell.Inthatsensestringsarejustaspecialcaseoflists,wherethelistelementsaresinglecharacters.Just remembertheconceptof clippingplaces,andtheindexesforslicingthingswillgetalotlessconfusing.

Examples
#T h i sp r o g r a mr e q u i r e sa ne x c e l l e n tu n d e r s t a n d i n go fd e c i m a ln u m b e r s d e ft o _ s t r i n g ( i n _ i n t ) : " " " C o n v e r t sa ni n t e g e rt oas t r i n g " " "
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 81/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

o u t _ s t r=" " p r e f i x=" " i fi n _ i n t<0 : p r e f i x=" " i n _ i n t=i n _ i n t w h i l ei n _ i n t/1 0! =0 : o u t _ s t r=c h r ( o r d ( ' 0 ' )+i n _ i n t%1 0 )+o u t _ s t r i n _ i n t=i n _ i n t/1 0 o u t _ s t r=c h r ( o r d ( ' 0 ' )+i n _ i n t%1 0 )+o u t _ s t r r e t u r np r e f i x+o u t _ s t r d e ft o _ i n t ( i n _ s t r ) : " " " C o n v e r t sas t r i n gt oa ni n t e g e r " " " o u t _ n u m=0 i fi n _ s t r [ 0 ]= =" " : m u l t i p l i e r=1 i n _ s t r=i n _ s t r [ 1 : ] e l s e : m u l t i p l i e r=1 f o rxi nr a n g e ( 0 ,l e n ( i n _ s t r ) ) : o u t _ n u m=o u t _ n u m*1 0+o r d ( i n _ s t r [ x ] )-o r d ( ' 0 ' ) r e t u r no u t _ n u m*m u l t i p l i e r p r i n tt o _ s t r i n g ( 2 ) p r i n tt o _ s t r i n g ( 2 3 4 4 5 ) p r i n tt o _ s t r i n g ( 2 3 4 4 5 ) p r i n tt o _ i n t ( " 1 4 2 3 4 " ) p r i n tt o _ i n t ( " 1 2 3 4 5 " ) p r i n tt o _ i n t ( " 3 5 1 2 " )

Theoutputis:
2 2 3 4 4 5 2 3 4 4 5 1 4 2 3 4 1 2 3 4 5 3 5 1 2

FileIO
HereisasimpleexampleoffileIO(input/output):
#W r i t eaf i l e o u t _ f i l e=o p e n ( " t e s t . t x t " ," w " ) o u t _ f i l e . w r i t e ( " T h i sT e x ti sg o i n gt oo u tf i l e \ n L o o ka ti ta n ds e e ! " ) o u t _ f i l e . c l o s e ( ) #R e a daf i l e i n _ f i l e=o p e n ( " t e s t . t x t " ," r " )
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 82/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

t e x t=i n _ f i l e . r e a d ( ) i n _ f i l e . c l o s e ( ) p r i n tt e x t

Theoutputandthecontentsofthefile t e s t . t x t are:
T h i sT e x ti sg o i n gt oo u tf i l e L o o ka ti ta n ds e e !

Noticethatitwroteafilecalled t e s t . t x t inthedirectorythatyourantheprogramfrom.The \ n inthestringtellsPythontoputa newlinewhereitis. AoverviewoffileIOis: Getafileobjectwiththe o p e n function. Readorwritetothefileobject(dependingonhowitwasopened) Closeit Thefirststepistogetafileobject.Thewaytodothisistousethe o p e n function.Theformatis f i l e _ o b j e c t=o p e n ( f i l e n a m e ,m o d e ) where f i l e _ o b j e c t isthevariable toputthefileobject, f i l e n a m e isastringwiththefilename,and m o d e is " r " to readafileor " w " to writeafile(andafewotherswewillskiphere).Nextthefile objectsfunctionscanbecalled.Thetwomostcommonfunctionsare r e a d and w r i t e .The w r i t e functionaddsastringtotheendofthefile.The r e a d function readsthenextthinginthefileandreturnsitasastring.Ifnoargumentisgivenitwillreturnthewholefile(asdoneintheexample). Nowhereisanewversionofthephonenumbersprogramthatwemadeearlier:
d e fp r i n t _ n u m b e r s ( n u m b e r s ) : p r i n t" T e l e p h o n eN u m b e r s : " f o rxi nn u m b e r s . k e y s ( ) : p r i n t" N a m e : " ,x ," \ t N u m b e r : " ,n u m b e r s [ x ] p r i n t d e fa d d _ n u m b e r ( n u m b e r s ,n a m e ,n u m b e r ) : n u m b e r s [ n a m e ]=n u m b e r d e fl o o k u p _ n u m b e r ( n u m b e r s ,n a m e ) : i fn a m ei nn u m b e r s : r e t u r n" T h en u m b e ri s"+n u m b e r s [ n a m e ] e l s e : r e t u r nn a m e+"w a sn o tf o u n d " d e fr e m o v e _ n u m b e r ( n u m b e r s ,n a m e ) : i fn a m ei nn u m b e r s : d e ln u m b e r s [ n a m e ] e l s e : p r i n tn a m e , "w a sn o tf o u n d " d e fl o a d _ n u m b e r s ( n u m b e r s ,f i l e n a m e ) :
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 83/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

i n _ f i l e=o p e n ( f i l e n a m e ," r " ) f o ri n _ l i n ei ni n _ f i l e : i n _ l i n e=i n _ l i n e . r s t r i p ( ' \ n ' )# E l i m i n a t ee n do fl i n eo re n t e r n a m e ,n u m b e r=i n _ l i n e . s p l i t ( " , " ) n u m b e r s [ n a m e ]=n u m b e r i n _ f i l e . c l o s e ( ) d e fs a v e _ n u m b e r s ( n u m b e r s ,f i l e n a m e ) : o u t _ f i l e=o p e n ( f i l e n a m e ," w " ) f o rxi nn u m b e r s . k e y s ( ) : o u t _ f i l e . w r i t e ( x+" , "+n u m b e r s [ x ]+" \ n " ) o u t _ f i l e . c l o s e ( ) d e fp r i n t _ m e n u ( ) : p r i n t' 1 .P r i n tP h o n eN u m b e r s ' p r i n t' 2 .A d daP h o n eN u m b e r ' p r i n t' 3 .R e m o v eaP h o n eN u m b e r ' p r i n t' 4 .L o o k u paP h o n eN u m b e r ' p r i n t' 5 .L o a dn u m b e r s ' p r i n t' 6 .S a v en u m b e r s ' p r i n t' 7 .Q u i t ' p r i n t p h o n e _ l i s t={ } m e n u _ c h o i c e=0 p r i n t _ m e n u ( ) w h i l eT r u e : m e n u _ c h o i c e=i n p u t ( " T y p ei nan u m b e r( 1 7 ) :" ) i fm e n u _ c h o i c e= =1 : p r i n t _ n u m b e r s ( p h o n e _ l i s t ) e l i fm e n u _ c h o i c e= =2 : p r i n t" A d dN a m ea n dN u m b e r " n a m e=r a w _ i n p u t ( " N a m e :" ) p h o n e=r a w _ i n p u t ( " N u m b e r :" ) a d d _ n u m b e r ( p h o n e _ l i s t ,n a m e ,p h o n e ) e l i fm e n u _ c h o i c e= =3 : p r i n t" R e m o v eN a m ea n dN u m b e r " n a m e=r a w _ i n p u t ( " N a m e :" ) r e m o v e _ n u m b e r ( p h o n e _ l i s t ,n a m e ) e l i fm e n u _ c h o i c e= =4 : p r i n t" L o o k u pN u m b e r " n a m e=r a w _ i n p u t ( " N a m e :" ) p r i n tl o o k u p _ n u m b e r ( p h o n e _ l i s t ,n a m e ) e l i fm e n u _ c h o i c e= =5 : f i l e n a m e=r a w _ i n p u t ( " F i l e n a m et ol o a d :" ) l o a d _ n u m b e r s ( p h o n e _ l i s t ,f i l e n a m e ) e l i fm e n u _ c h o i c e= =6 : f i l e n a m e=r a w _ i n p u t ( " F i l e n a m et os a v e :" ) s a v e _ n u m b e r s ( p h o n e _ l i s t ,f i l e n a m e ) e l i fm e n u _ c h o i c e= =7 : b r e a k e l s e : p r i n t _ m e n u ( ) p r i n t" G o o d b y e "

en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version

84/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

Noticethatitnowincludessavingandloadingfiles.Hereissomeoutputofmyrunningittwice:
1 .P r i n tP h o n eN u m b e r s 2 .A d daP h o n eN u m b e r 3 .R e m o v eaP h o n eN u m b e r 4 .L o o k u paP h o n eN u m b e r 5 .L o a dn u m b e r s 6 .S a v en u m b e r s 7 .Q u i t T y p ei nan u m b e r( 1 7 ) :2 A d dN a m ea n dN u m b e r N a m e :J i l l N u m b e r :1 2 3 4 T y p ei nan u m b e r( 1 7 ) :2 A d dN a m ea n dN u m b e r N a m e :F r e d N u m b e r :4 3 2 1 T y p ei nan u m b e r( 1 7 ) :1 T e l e p h o n eN u m b e r s : N a m e :J i l l N u m b e r :1 2 3 4 N a m e :F r e d N u m b e r :4 3 2 1 T y p ei nan u m b e r( 1 7 ) :6 F i l e n a m et os a v e :n u m b e r s . t x t T y p ei nan u m b e r( 1 7 ) :7 G o o d b y e

1 .P r i n tP h o n eN u m b e r s 2 .A d daP h o n eN u m b e r 3 .R e m o v eaP h o n eN u m b e r 4 .L o o k u paP h o n eN u m b e r 5 .L o a dn u m b e r s 6 .S a v en u m b e r s 7 .Q u i t T y p ei nan u m b e r( 1 7 ) :5 F i l e n a m et ol o a d :n u m b e r s . t x t T y p ei nan u m b e r( 1 7 ) :1 T e l e p h o n eN u m b e r s : N a m e :J i l l N u m b e r :1 2 3 4 N a m e :F r e d N u m b e r :4 3 2 1 T y p ei nan u m b e r( 1 7 ) :7 G o o d b y e

Thenewportionsofthisprogramare:
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 85/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

d e fl o a d _ n u m b e r s ( n u m b e r s ,f i l e n a m e ) : i n _ f i l e=o p e n ( f i l e n a m e ," r " ) w h i l eT r u e : i n _ l i n e=i n _ f i l e . r e a d l i n e ( ) i fn o ti n _ l i n e : b r e a k i n _ l i n e=i n _ l i n e [ : 1 ] n a m e ,n u m b e r=i n _ l i n e . s p l i t ( " , " ) n u m b e r s [ n a m e ]=n u m b e r i n _ f i l e . c l o s e ( ) d e fs a v e _ n u m b e r s ( n u m b e r s ,f i l e n a m e ) : o u t _ f i l e=o p e n ( f i l e n a m e ," w " ) f o rxi nn u m b e r s . k e y s ( ) : o u t _ f i l e . w r i t e ( x+" , "+n u m b e r s [ x ]+" \ n " ) o u t _ f i l e . c l o s e ( )

Firstwewilllookatthesaveportionoftheprogram.Firstitcreatesafileobjectwiththecommand o p e n ( f i l e n a m e ," w " ) .Nextitgoesthroughandcreatesaline foreachofthephonenumberswiththecommand o u t _ f i l e . w r i t e ( x+" , "+n u m b e r s [ x ]+" \ n " ) .Thiswritesoutalinethatcontainsthename,acomma,thenumber andfollowsitbyanewline. Theloadingportionisalittlemorecomplicated.Itstartsbygettingafileobject.Thenitusesa w h i l eT r u e : looptokeeploopinguntila b r e a k statementis encountered.Nextitgetsalinewiththeline i n _ l i n e=i n _ f i l e . r e a d l i n e ( ) .The r e a d l i n e functionwillreturnaemptystringwhentheendofthefileisreached.The i f statementchecksforthisand b r e a k soutofthe w h i l e loopwhenthathappens.Ofcourseifthe r e a d l i n e functiondidnotreturnthenewlineattheendofthe linetherewouldbenowaytotellifanemptystringwasanemptylineortheendofthefilesothenewlineisleftinwhat r e a d l i n e returns.Hencewehavetoget ridofthenewline.Theline i n _ l i n e=i n _ l i n e [ : 1 ] doesthisforusbydroppingthelastcharacter.Nexttheline n a m e ,n u m b e r=i n _ l i n e . s p l i t ( " , " ) splitsthelineatthe commaintoanameandanumber.Thisisthenaddedtothe n u m b e r s dictionary.

Exercises
NowmodifythegradesprogramfromsectionDictionariessothatitusesfileIOtokeeparecordofthestudents. Solution NowmodifythegradesprogramfromsectionDictionariessothatitusesfileIOtokeeparecordofthestudents.

a s s i g n m e n t s=[ ' h wc h1 ' ,' h wc h2 ' ,' q u i z ' ,' h wc h3 ' ,' t e s t ' ] s t u d e n t s={} d e fl o a d _ g r a d e s ( g r a d e s f i l e ) : i n p u t f i l e=o p e n ( g r a d e s f i l e ," r " ) g r a d e s=[] w h i l eT r u e : s t u d e n t _ a n d _ g r a d e=i n p u t f i l e . r e a d l i n e ( ) s t u d e n t _ a n d _ g r a d e=s t u d e n t _ a n d _ g r a d e [ : 1 ] i fn o ts t u d e n t _ a n d _ g r a d e : b r e a k
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 86/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

e l s e : s t u d e n t n a m e ,s t u d e n t g r a d e s=s t u d e n t _ a n d _ g r a d e . s p l i t ( " , " ) s t u d e n t g r a d e s=s t u d e n t g r a d e s . s p l i t ( "" ) s t u d e n t s [ s t u d e n t n a m e ]=s t u d e n t g r a d e s i n p u t f i l e . c l o s e ( ) p r i n t" G r a d e sl o a d e d . " d e fs a v e _ g r a d e s ( g r a d e s f i l e ) : o u t p u t f i l e=o p e n ( g r a d e s f i l e ," w " ) f o rii ns t u d e n t s . k e y s ( ) : o u t p u t f i l e . w r i t e ( i+" , " ) f o rxi ns t u d e n t s [ i ] : o u t p u t f i l e . w r i t e ( x+" , " )# a d d e dm i s s i n gc o m m a o u t p u t f i l e . w r i t e ( " \ n " ) o u t p u t f i l e . c l o s e ( ) p r i n t" G r a d e ss a v e d . " d e fp r i n t _ m e n u ( ) : p r i n t" 1 .A d ds t u d e n t " p r i n t" 2 .R e m o v es t u d e n t " p r i n t" 3 .L o a dg r a d e s " p r i n t" 4 .R e c o r dg r a d e " p r i n t" 5 .P r i n tg r a d e s " p r i n t" 6 .S a v eg r a d e s " p r i n t" 7 .P r i n tM e n u " p r i n t" 9 .Q u i t " d e fp r i n t _ a l l _ g r a d e s ( ) : k e y s=s t u d e n t s . k e y s ( ) i fk e y s : k e y s . s o r t ( ) p r i n t' \ t ' , f o rii nr a n g e ( l e n ( a s s i g n m e n t s ) ) : p r i n ta s s i g n m e n t s [ i ] ,' \ t ' , p r i n t f o rxi nk e y s : p r i n tx ,' \ t ' , g r a d e s=s t u d e n t s [ x ] p r i n t _ g r a d e s ( g r a d e s ) e l s e : p r i n t" T h e r ea r en og r a d e st op r i n t . " d e fp r i n t _ g r a d e s ( g r a d e s ) : f o rii nr a n g e ( l e n ( g r a d e s ) ) : p r i n tg r a d e s [ i ] ,' \ t ' , p r i n t p r i n t _ m e n u ( ) m e n u _ c h o i c e=0 w h i l em e n u _ c h o i c e! =9 : p r i n t m e n u _ c h o i c e=i n p u t ( " M e n uC h o i c e :" ) i fm e n u _ c h o i c e= =1 : n a m e=r a w _ i n p u t ( " S t u d e n tt oa d d :" ) s t u d e n t s [ n a m e ]=[ 0 ]*l e n ( a s s i g n m e n t s ) e l i fm e n u _ c h o i c e= =2 :
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 87/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

n a m e=r a w _ i n p u t ( " S t u d e n tt or e m o v e :" ) i fn a m ei ns t u d e n t s : d e ls t u d e n t s [ n a m e ] e l s e : p r i n t" S t u d e n t : " ,n a m e ," n o tf o u n d " e l i fm e n u _ c h o i c e= =3 : g r a d e s f i l e=r a w _ i n p u t ( " L o a dg r a d e sf r o mw h i c hf i l e ?" ) l o a d _ g r a d e s ( g r a d e s f i l e ) e l i fm e n u _ c h o i c e= =4 : p r i n t" R e c o r dG r a d e " n a m e=r a w _ i n p u t ( " S t u d e n t :" ) i fn a m ei ns t u d e n t s : g r a d e s=s t u d e n t s [ n a m e ] p r i n t" T y p ei nt h en u m b e ro ft h eg r a d et or e c o r d " p r i n t" T y p ea0( z e r o )t oe x i t " f o rii nr a n g e ( l e n ( a s s i g n m e n t s ) ) : p r i n ti+1 ,a s s i g n m e n t s [ i ] ,' \ t ' , p r i n t p r i n t _ g r a d e s ( g r a d e s ) w h i c h=1 2 3 4 w h i l ew h i c h! =1 : w h i c h=i n p u t ( " C h a n g ew h i c hG r a d e :" ) w h i c h=w h i c h-1 i f0< =w h i c h<l e n ( g r a d e s ) : g r a d e=r a w _ i n p u t ( " G r a d e :" )#C h a n g ef r o mi n p u t ( )t or a w _ i n p u t ( )t oa v o i da ne r r o rw h e ns a v i n g g r a d e s [ w h i c h ]=g r a d e e l i fw h i c h! =1 : p r i n t" I n v a l i dG r a d eN u m b e r " e l s e : p r i n t" S t u d e n tn o tf o u n d " e l i fm e n u _ c h o i c e= =5 : p r i n t _ a l l _ g r a d e s ( ) e l i fm e n u _ c h o i c e= =6 : g r a d e s f i l e=r a w _ i n p u t ( " S a v eg r a d e st ow h i c hf i l e ?" ) s a v e _ g r a d e s ( g r a d e s f i l e ) e l i fm e n u _ c h o i c e! =9 : p r i n t _ m e n u ( )

Dealingwiththeimperfect
...orhowtohandleerrors
Soyounowhavetheperfectprogram,itrunsflawlessly,exceptforonedetail,itwillcrashoninvaliduserinput.Havenofear,forPythonhasaspecialcontrol structureforyou.It'scalled t r y andittriestodosomething.Hereisanexampleofaprogramwithaproblem:
p r i n t" T y p eC o n t r o lCo r1t oe x i t " n u m b e r=1 w h i l en u m b e r! =1 :
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 88/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

n u m b e r=i n t ( r a w _ i n p u t ( " E n t e ran u m b e r :" ) ) p r i n t" Y o ue n t e r e d : " ,n u m b e r

Noticehowwhenyouenter @ # & itoutputssomethinglike:


T r a c e b a c k( i n n e r m o s tl a s t ) : F i l e" t r y _ l e s s . p y " ,l i n e4 ,i n? n u m b e r=i n t ( r a w _ i n p u t ( " E n t e ran u m b e r :" ) ) < / s o u r c e > V a l u e E r r o r :i n v a l i dl i t e r a lf o ri n t ( ) :@ # &

Asyoucanseethe i n t ( ) functionisunhappywiththenumber @ # & (aswellitshouldbe).ThelastlineshowswhattheproblemisPythonfounda V a l u e E r r o r .How canourprogramdealwiththis?Whatwedoisfirst:puttheplacewheretheerrorsoccursina t r y block,andsecond:tellPythonhowwewant V a l u e E r r o r s handled.Thefollowingprogramdoesthis:


p r i n t" T y p eC o n t r o lCo r1t oe x i t " n u m b e r=1 w h i l en u m b e r! =1 : t r y : n u m b e r=i n t ( r a w _ i n p u t ( " E n t e ran u m b e r :" ) ) p r i n t" Y o ue n t e r e d : " ,n u m b e r e x c e p tV a l u e E r r o r : p r i n t" T h a tw a sn o tan u m b e r . "

Nowwhenwerunthenewprogramandgiveit @ # & ittellsus"Thatwasnotanumber."andcontinueswithwhatitwasdoingbefore. Whenyourprogramkeepshavingsomeerrorthatyouknowhowtohandle,putcodeina t r y block,andputthewaytohandletheerrorinthe e x c e p t block. HereisamorecomplexexampleofErrorHandling.


#P r o g r a mb yM i t c h e l lA i k e n s2 0 1 2 #N oc o p y r i g h t . i m p o r tm a t h d e fm a i n ( ) : s u c c e s s=0 w h i l e( s u c c e s s= =0 ) : t r y : e p a c t ( ) s u c c e s s=1 e x c e p tV a l u e E r r o r : p r i n t" E r r o r .P l e a s ee n t e ra ni n t e g e rv a l u e . " y e a r=0 e x c e p tN a m e E r r o r : p r i n t" E r r o r .P l e a s ee n t e ra ni n t e g e rv a l u e . " y e a r=0 e x c e p tS y n t a x E r r o r :
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 89/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

p r i n t" E r r o r .P l e a s ee n t e ra ni n t e g e rv a l u e . " y e a r=0 f i n a l l y : p r i n t" P r o g r a mC o m p l e t e " d e fe p a c t ( ) : y e a r=i n t ( i n p u t ( " W h a ty e a ri si t ? \ n " ) ) C=y e a r / 1 0 0 e p a c t v a l=( 8+( C / 4 )-C+( ( 8 * C+1 3 ) / 2 5 )+1 1*( y e a r % 1 9 ) ) % 3 0 p r i n t" T h eE p a c ti s :" , e p a c t v a l m a i n ( )

Theprogramaboveusesconceptsfrompreviouslessonsaswellasthecurrentlesson.Let'slookattheaboveprograminsections. Afterwedefinethefunctioncalled"main",wetellitthatwewantto"try"functionnamed"epact".Itdoesso"while"thereisno"success".Theinterpreterthen goestothetheline y e a r=i n t ( i n p u t ( " W h a ty e a ri si t ? \ n " ) ) .Theinterpretertakesthevalueenteredbytheuserandstoresitinthevariablenamed"year". Ifthevalueenteredisnotanintegerorafloatingpointnumber(whichwouldbeconvertedtoanintegerbytheinterpreter),anexceptionwouldberaised,and executionofthe t r y blockends,justbefore s u c c e s s isassignedthevalue1. Let'slookatsomepossibleexceptions.theprogramabovedoesnothavean e x c e p t clauseforeverypossibleexception,astherearenumeroustypesor exceptions. Ifthevalueenteredforyearisanalphabeticalcharacter,a N a m e E r r o r exceptionisraised.Intheprogramabove,thisiscaughtbythe e x c e p tN a m e E r r o r : line,and theinterpreterexecutestheprintstatementbelowthe e x c e p tN a m e E r r o r : ,thenitsetsthevalueof"year"to0asaprecaution,clearingitofanynonnumeric number.Theinterpreterthenjumpsbacktothefirstlineofthe w h i l e loop,andtheprocessrestarts. Theprocessabovewouldbethesamefortheotherexceptionswehave.Ifanexceptionisraised,andthereisanexceptclauseforitinourprogram,the interpreterwilljumptothestatementsundertheappropriateexceptclause,andexecutethem. The f i n a l l y statement,issometimesusedinexceptionhandlingaswell.Thinkofitasthetrumpcard.Statementsunderneaththe f i n a l l y clausewillbe executedregardlessofifweraiseandexceptionornot.The f i n a l l y statementwillbeexecutedafterany t r y or e x c e p t clausespriortoit. Belowisasimplerexamplewherewearenotlooped,andthe f i n a l l y clauseisexecutedregardlessofexceptions.
# P r o g r a mB yM i t c h e l lA i k e n s2 0 1 2 # N o tc o p y r i g h t . d e fm a i n ( ) : t r y : n u m b e r=i n t ( i n p u t ( " P l e a s ee n t e ran u m b e r . \ n " ) ) h a l f=n u m b e r / 2 p r i n t" H a l fo ft h en u m b e ry o ue n t e r e di s" , h a l f e x c e p tN a m e E r r o r : p r i n t" E r r o r . " e x c e p tV a l u e E r r o r : p r i n t" E r r o r . "
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 90/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

e x c e p tS y n t a x E r r o r : p r i n t" E r r o r . " f i n a l l y : p r i n t" Ia me x e c u t i n gt h ef i n a l l yc l a u s e . " m a i n ( )

Ifweweretoenteranalphabeticvaluefor n u m b e r=i n t ( i n p u t ( " P l e a s ee n t e ran u m b e r . \ n " ) ) ,theoutputwouldbeasfollows:


P l e a s ee n t e ran u m b e r . t E r r o r . Ia me x e c u t i n gt h ef i n a l l yc l a u s e .

Exercises
Updateatleastthephonenumbersprogram(insectionFileIO)soitdoesn'tcrashifauserdoesn'tenteranydataatthemenu.

TheEnd
ForthemomentIrecommendlookingatThePythonTutorial(http://docs.python.org/tut/tut.html)byGuidovanRossum(http://www.python.org/~guido/)for moretopics.Ifyouhavebeenfollowingthistutorial,youshouldbeabletounderstandafairamountofit.IfyouwanttogetdeeperintoPython,DiveInto Python(http://www.diveintopython.net/)isaniceonlinetextbook,althoughtargetedatpeoplewithamoresolidprogrammingbackground.ThePython Programmingwikibookcanbeworthlookingat,too. Thistutorialisverymuchaworkinprogress.Thankstoeveryonewhohassentmeemailsaboutit.Ienjoyedreadingthem,evenwhenIhavenotalwaysbeen thebestreplier. Happyprogramming,mayitchangeyourlifeandtheworld.

FAQ
Question: Can'tuseprogramswithinput. Answer: IfyouareusingIDLEthentryusingcommandline.ThisproblemseemstobefixedinIDLE0.6andnewer.Ifyouareusinganolderversionof IDLEtryupgradingtoPython2.0ornewer. Isthereaprintableversion? Yes,seethenextquestion. IsthereaPDForzippedversion? Yes,gotohttp://www.honors.montana.edu/~jjc/easytutforseveraldifferentversions.NotethatthiswillnotalwaysbeuptodatewiththeWikibooks
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 91/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

version.TheWikibookcanbeprintedfromthe printversion. Whatisthetutorialwrittenwith? Originally,LaTeX,seethe e a s y t u t . t e x file. Ican'ttypeinprogramsofmorethanoneline. Iftheprogramsthatyoutypeinrunassoonasyouaretypingthemin,youneedtoeditafileinsteadoftypingthemininteractivemode.(Hint: interactivemodeisthemodewiththe > > > promptinfrontofit.) Myquestionisnotansweredhere. Askonthetalkpage.Pleasepostsourcecodeifatallrelevant(even,(ormaybeespecially)ifitdoesn'twork).Helpfulthingstoincludearewhatyou weretryingtodo,whathappened,whatyouexpectedtohappen,errormessages,versionofPython,OperatingSystem,andwhetherornotyourcat wassteppingonthekeyboard.(Thecatinmyhousehasafondnessforspacebarsandcontrolkeys.) Iwanttoreaditinadifferentlanguage. ThereareseveraltranslationsthatIknowof.OneisinKoreanandisavailableathttp://home.hanmir.com/~johnsonj/easytut/easytut.html.Anotherisin Spanishandathttp://www.honors.montana.edu/~jjc/easytut/easytut_es/.AnotherisinItalianandisavailableat http://www.python.it/doc/tut_begin/index.html.AnotherisinGreekandavailableathttp://www.honors.montana.edu/~jjc/easytut/easytut_gr/.Several peoplehavesaidtheyaredoingatranslationinotherlanguagessuchasFrench,butIneverheardbackfromthem.Ifyouhavedoneatranslationor knowofanytranslations,pleaseeithersendittomeorsendmealink. HowdoImakeaGUIinPython? YoucanuseeitherTKinterathttp://www.python.org/topics/tkinter/orWXPythonathttp://www.wxpython.org/ HowdoImakeagameinPython? ThebestmethodisprobablytousePYgameathttp://pygame.org/ HowdoImakeanexecutablefromaPythonprogram? Shortanswer:Pythonisaninterpretedlanguagesothatisimpossible.Longansweristhatsomethingsimilartoanexecutablecanbecreatedbytaking thePythoninterpreterandthefileandjoiningthemtogetheranddistributingthat.Formoreonthatproblemseehttp://www.python.org/cgibin/faqw.py? req=all#4.28.Aprojectthatdoesmakeexecutablepythonfilesispy2exeseehttp://www.py2exe.org. Ineedhelpwiththeexercises Hint,thepasswordprogramrequirestwovariables,onetokeeptrackofthenumberoftimesthepasswordwastypedin,andanothertokeeptrackof thelastpasswordtypedin.Alsoyoucandownloadsolutionsfromhttp://www.honors.montana.edu/~jjc/easytut/ Whatandwhenwasthelastthingchanged? 2000Dec16,addederrorhandlingchapter. 2000Dec22,Removedoldinstallprocedure. 2001Jan16,Fixedbuginprogram,Addedexampleanddatatolistssection. 2001Apr5,Spelling,grammar,addedanotherhowtobreakprograms,urlfixforPDFversion. 2001May13,Addedchapterondebugging. 2001Nov11,Addedexercises,fixedgrammar,spelling,andhopefullyimprovedexplanationsofsomethings. 2001Nov19,Addedpasswordexercise,revisedreferencessection.
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 92/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

2002Feb23,Moved3timespasswordexercise,changedltolistinlistexamplesquestion.AddedanewexampletoDecisionschapter,addedtwonew exercises. 2002Mar14,Changedabstomy_abssincepythonnowdefinesaabsfunction. 2002May15,Addedafaqaboutcreatinganexecutable.Addedacommentfromaboutthelistexample.FixedtyposfromAxelKleiboemer. 2002Jun14,Changedaprogramtousewhiletrueinsteadofwhile1tobemoreclear. 2002Jul5,Rewrotefunctionschapter.Modifiedfibprogramtohopefullybeclearer. 2003Jan3,Addedaverageexamplestothedecisionschapter. 2003Jan19,Addedcommentaboutvalueofa_var.Fixedmistakeinaverage2.pyprogram. 2003Sep5,ChangedidleinstructiontoRun>RunModule. 2004Jun1,PutonWikibooks SincethenallchangesarevisiblethroughtheWikibooksversionkeepingsystem.

License
TheNonProgrammer'sTutorialforPythonislicensedundertheGNUFreeDocumentationLicense.Allprogrammingexamplesinthetextaregrantedtothe publicdomain.

GNUFreeDocumentationLicense
Version1.3,3November2008Copyright(C)2000,2001,2002,2007,2008FreeSoftwareFoundation,Inc.<http://fsf.org/> Everyoneispermittedtocopyanddistributeverbatimcopiesofthislicensedocument,butchangingitisnotallowed.

0.PREAMBLE
ThepurposeofthisLicenseistomakeamanual,textbook,orotherfunctionalandusefuldocument"free"inthesenseoffreedom:toassureeveryonethe effectivefreedomtocopyandredistributeit,withorwithoutmodifyingit,eithercommerciallyornoncommercially.Secondarily,thisLicensepreservesforthe authorandpublisherawaytogetcreditfortheirwork,whilenotbeingconsideredresponsibleformodificationsmadebyothers. ThisLicenseisakindof"copyleft",whichmeansthatderivativeworksofthedocumentmustthemselvesbefreeinthesamesense.ItcomplementstheGNU GeneralPublicLicense,whichisacopyleftlicensedesignedforfreesoftware. WehavedesignedthisLicenseinordertouseitformanualsforfreesoftware,becausefreesoftwareneedsfreedocumentation:afreeprogramshouldcome withmanualsprovidingthesamefreedomsthatthesoftwaredoes.ButthisLicenseisnotlimitedtosoftwaremanualsitcanbeusedforanytextualwork, regardlessofsubjectmatterorwhetheritispublishedasaprintedbook.WerecommendthisLicenseprincipallyforworkswhosepurposeisinstructionor reference.

1.APPLICABILITYANDDEFINITIONS
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 93/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

ThisLicenseappliestoanymanualorotherwork,inanymedium,thatcontainsanoticeplacedbythecopyrightholdersayingitcanbedistributedunderthe termsofthisLicense.Suchanoticegrantsaworldwide,royaltyfreelicense,unlimitedinduration,tousethatworkundertheconditionsstatedherein.The "Document",below,referstoanysuchmanualorwork.Anymemberofthepublicisalicensee,andisaddressedas"you".Youacceptthelicenseifyoucopy, modifyordistributetheworkinawayrequiringpermissionundercopyrightlaw. A"ModifiedVersion"oftheDocumentmeansanyworkcontainingtheDocumentoraportionofit,eithercopiedverbatim,orwithmodificationsand/or translatedintoanotherlanguage. A"SecondarySection"isanamedappendixorafrontmattersectionoftheDocumentthatdealsexclusivelywiththerelationshipofthepublishersorauthors oftheDocumenttotheDocument'soverallsubject(ortorelatedmatters)andcontainsnothingthatcouldfalldirectlywithinthatoverallsubject.(Thus,ifthe Documentisinpartatextbookofmathematics,aSecondarySectionmaynotexplainanymathematics.)Therelationshipcouldbeamatterofhistorical connectionwiththesubjectorwithrelatedmatters,oroflegal,commercial,philosophical,ethicalorpoliticalpositionregardingthem. The"InvariantSections"arecertainSecondarySectionswhosetitlesaredesignated,asbeingthoseofInvariantSections,inthenoticethatsaysthatthe DocumentisreleasedunderthisLicense.IfasectiondoesnotfittheabovedefinitionofSecondarythenitisnotallowedtobedesignatedasInvariant.The DocumentmaycontainzeroInvariantSections.IftheDocumentdoesnotidentifyanyInvariantSectionsthentherearenone. The"CoverTexts"arecertainshortpassagesoftextthatarelisted,asFrontCoverTextsorBackCoverTexts,inthenoticethatsaysthattheDocumentis releasedunderthisLicense.AFrontCoverTextmaybeatmost5words,andaBackCoverTextmaybeatmost25words. A"Transparent"copyoftheDocumentmeansamachinereadablecopy,representedinaformatwhosespecificationisavailabletothegeneralpublic,thatis suitableforrevisingthedocumentstraightforwardlywithgenerictexteditorsor(forimagescomposedofpixels)genericpaintprogramsor(fordrawings)some widelyavailabledrawingeditor,andthatissuitableforinputtotextformattersorforautomatictranslationtoavarietyofformatssuitableforinputtotext formatters.AcopymadeinanotherwiseTransparentfileformatwhosemarkup,orabsenceofmarkup,hasbeenarrangedtothwartordiscouragesubsequent modificationbyreadersisnotTransparent.AnimageformatisnotTransparentifusedforanysubstantialamountoftext.Acopythatisnot"Transparent"is called"Opaque". ExamplesofsuitableformatsforTransparentcopiesincludeplainASCIIwithoutmarkup,Texinfoinputformat,LaTeXinputformat,SGMLorXMLusinga publiclyavailableDTD,andstandardconformingsimpleHTML,PostScriptorPDFdesignedforhumanmodification.Examplesoftransparentimageformats includePNG,XCFandJPG.Opaqueformatsincludeproprietaryformatsthatcanbereadandeditedonlybyproprietarywordprocessors,SGMLorXMLfor whichtheDTDand/orprocessingtoolsarenotgenerallyavailable,andthemachinegeneratedHTML,PostScriptorPDFproducedbysomewordprocessors foroutputpurposesonly. The"TitlePage"means,foraprintedbook,thetitlepageitself,plussuchfollowingpagesasareneededtohold,legibly,thematerialthisLicenserequiresto appearinthetitlepage.Forworksinformatswhichdonothaveanytitlepageassuch,"TitlePage"meansthetextnearthemostprominentappearanceof thework'stitle,precedingthebeginningofthebodyofthetext. The"publisher"meansanypersonorentitythatdistributescopiesoftheDocumenttothepublic. Asection"EntitledXYZ"meansanamedsubunitoftheDocumentwhosetitleeitherispreciselyXYZorcontainsXYZinparenthesesfollowingtextthat translatesXYZinanotherlanguage.(HereXYZstandsforaspecificsectionnamementionedbelow,suchas"Acknowledgements","Dedications", "Endorsements",or"History".)To"PreservetheTitle"ofsuchasectionwhenyoumodifytheDocumentmeansthatitremainsasection"EntitledXYZ" accordingtothisdefinition.

TheDocumentmayincludeWarrantyDisclaimersnexttothenoticewhichstatesthatthisLicenseappliestotheDocument.TheseWarrantyDisclaimersare 94/99 en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

TheDocumentmayincludeWarrantyDisclaimersnexttothenoticewhichstatesthatthisLicenseappliestotheDocument.TheseWarrantyDisclaimersare consideredtobeincludedbyreferenceinthisLicense,butonlyasregardsdisclaimingwarranties:anyotherimplicationthattheseWarrantyDisclaimersmay haveisvoidandhasnoeffectonthemeaningofthisLicense.

2.VERBATIMCOPYING
YoumaycopyanddistributetheDocumentinanymedium,eithercommerciallyornoncommercially,providedthatthisLicense,thecopyrightnotices,andthe licensenoticesayingthisLicenseappliestotheDocumentarereproducedinallcopies,andthatyouaddnootherconditionswhatsoevertothoseofthis License.Youmaynotusetechnicalmeasurestoobstructorcontrolthereadingorfurthercopyingofthecopiesyoumakeordistribute.However,youmay acceptcompensationinexchangeforcopies.Ifyoudistributealargeenoughnumberofcopiesyoumustalsofollowtheconditionsinsection3. Youmayalsolendcopies,underthesameconditionsstatedabove,andyoumaypubliclydisplaycopies.

3.COPYINGINQUANTITY
Ifyoupublishprintedcopies(orcopiesinmediathatcommonlyhaveprintedcovers)oftheDocument,numberingmorethan100,andtheDocument'slicense noticerequiresCoverTexts,youmustenclosethecopiesincoversthatcarry,clearlyandlegibly,alltheseCoverTexts:FrontCoverTextsonthefrontcover, andBackCoverTextsonthebackcover.Bothcoversmustalsoclearlyandlegiblyidentifyyouasthepublisherofthesecopies.Thefrontcovermustpresent thefulltitlewithallwordsofthetitleequallyprominentandvisible.Youmayaddothermaterialonthecoversinaddition.Copyingwithchangeslimitedtothe covers,aslongastheypreservethetitleoftheDocumentandsatisfytheseconditions,canbetreatedasverbatimcopyinginotherrespects. Iftherequiredtextsforeithercoveraretoovoluminoustofitlegibly,youshouldputthefirstoneslisted(asmanyasfitreasonably)ontheactualcover,and continuetherestontoadjacentpages. IfyoupublishordistributeOpaquecopiesoftheDocumentnumberingmorethan100,youmusteitherincludeamachinereadableTransparentcopyalong witheachOpaquecopy,orstateinorwitheachOpaquecopyacomputernetworklocationfromwhichthegeneralnetworkusingpublichasaccessto downloadusingpublicstandardnetworkprotocolsacompleteTransparentcopyoftheDocument,freeofaddedmaterial.Ifyouusethelatteroption,youmust takereasonablyprudentsteps,whenyoubegindistributionofOpaquecopiesinquantity,toensurethatthisTransparentcopywillremainthusaccessibleat thestatedlocationuntilatleastoneyearafterthelasttimeyoudistributeanOpaquecopy(directlyorthroughyouragentsorretailers)ofthateditiontothe public. Itisrequested,butnotrequired,thatyoucontacttheauthorsoftheDocumentwellbeforeredistributinganylargenumberofcopies,togivethemachanceto provideyouwithanupdatedversionoftheDocument.

4.MODIFICATIONS
YoumaycopyanddistributeaModifiedVersionoftheDocumentundertheconditionsofsections2and3above,providedthatyoureleasetheModified VersionunderpreciselythisLicense,withtheModifiedVersionfillingtheroleoftheDocument,thuslicensingdistributionandmodificationoftheModified Versiontowhoeverpossessesacopyofit.Inaddition,youmustdothesethingsintheModifiedVersion: A. UseintheTitlePage(andonthecovers,ifany)atitledistinctfromthatoftheDocument,andfromthoseofpreviousversions(whichshould,ifthere wereany,belistedintheHistorysectionoftheDocument).Youmayusethesametitleasapreviousversioniftheoriginalpublisherofthatversion givespermission. B. ListontheTitlePage,asauthors,oneormorepersonsorentitiesresponsibleforauthorshipofthemodificationsintheModifiedVersion,togetherwith
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 95/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

C. D. E. F. G. H. I.

J.

K. L. M. N. O.

atleastfiveoftheprincipalauthorsoftheDocument(allofitsprincipalauthors,ifithasfewerthanfive),unlesstheyreleaseyoufromthisrequirement. StateontheTitlepagethenameofthepublisheroftheModifiedVersion,asthepublisher. PreserveallthecopyrightnoticesoftheDocument. Addanappropriatecopyrightnoticeforyourmodificationsadjacenttotheothercopyrightnotices. Include,immediatelyafterthecopyrightnotices,alicensenoticegivingthepublicpermissiontousetheModifiedVersionunderthetermsofthis License,intheformshownintheAddendumbelow. PreserveinthatlicensenoticethefulllistsofInvariantSectionsandrequiredCoverTextsgivenintheDocument'slicensenotice. IncludeanunalteredcopyofthisLicense. PreservethesectionEntitled"History",PreserveitsTitle,andaddtoitanitemstatingatleastthetitle,year,newauthors,andpublisherofthe ModifiedVersionasgivenontheTitlePage.IfthereisnosectionEntitled"History"intheDocument,createonestatingthetitle,year,authors,and publisheroftheDocumentasgivenonitsTitlePage,thenaddanitemdescribingtheModifiedVersionasstatedintheprevioussentence. Preservethenetworklocation,ifany,givenintheDocumentforpublicaccesstoaTransparentcopyoftheDocument,andlikewisethenetwork locationsgivenintheDocumentforpreviousversionsitwasbasedon.Thesemaybeplacedinthe"History"section.Youmayomitanetworklocation foraworkthatwaspublishedatleastfouryearsbeforetheDocumentitself,oriftheoriginalpublisheroftheversionitreferstogivespermission. ForanysectionEntitled"Acknowledgements"or"Dedications",PreservetheTitleofthesection,andpreserveinthesectionallthesubstanceandtone ofeachofthecontributoracknowledgementsand/ordedicationsgiventherein. PreservealltheInvariantSectionsoftheDocument,unalteredintheirtextandintheirtitles.Sectionnumbersortheequivalentarenotconsideredpart ofthesectiontitles. DeleteanysectionEntitled"Endorsements".SuchasectionmaynotbeincludedintheModifiedversion. DonotretitleanyexistingsectiontobeEntitled"Endorsements"ortoconflictintitlewithanyInvariantSection. PreserveanyWarrantyDisclaimers.

IftheModifiedVersionincludesnewfrontmattersectionsorappendicesthatqualifyasSecondarySectionsandcontainnomaterialcopiedfromthe Document,youmayatyouroptiondesignatesomeorallofthesesectionsasinvariant.Todothis,addtheirtitlestothelistofInvariantSectionsinthe ModifiedVersion'slicensenotice.Thesetitlesmustbedistinctfromanyothersectiontitles. YoumayaddasectionEntitled"Endorsements",provideditcontainsnothingbutendorsementsofyourModifiedVersionbyvariouspartiesforexample, statementsofpeerrevieworthatthetexthasbeenapprovedbyanorganizationastheauthoritativedefinitionofastandard. YoumayaddapassageofuptofivewordsasaFrontCoverText,andapassageofupto25wordsasaBackCoverText,totheendofthelistofCover TextsintheModifiedVersion.OnlyonepassageofFrontCoverTextandoneofBackCoverTextmaybeaddedby(orthrougharrangementsmadeby)any oneentity.IftheDocumentalreadyincludesacovertextforthesamecover,previouslyaddedbyyouorbyarrangementmadebythesameentityyouare actingonbehalfof,youmaynotaddanotherbutyoumayreplacetheoldone,onexplicitpermissionfromthepreviouspublisherthataddedtheoldone. Theauthor(s)andpublisher(s)oftheDocumentdonotbythisLicensegivepermissiontousetheirnamesforpublicityforortoassertorimplyendorsementof anyModifiedVersion.

5.COMBININGDOCUMENTS
YoumaycombinetheDocumentwithotherdocumentsreleasedunderthisLicense,underthetermsdefinedinsection4aboveformodifiedversions,provided en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 96/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

YoumaycombinetheDocumentwithotherdocumentsreleasedunderthisLicense,underthetermsdefinedinsection4aboveformodifiedversions,provided thatyouincludeinthecombinationalloftheInvariantSectionsofalloftheoriginaldocuments,unmodified,andlistthemallasInvariantSectionsofyour combinedworkinitslicensenotice,andthatyoupreservealltheirWarrantyDisclaimers. ThecombinedworkneedonlycontainonecopyofthisLicense,andmultipleidenticalInvariantSectionsmaybereplacedwithasinglecopy.Ifthereare multipleInvariantSectionswiththesamenamebutdifferentcontents,makethetitleofeachsuchsectionuniquebyaddingattheendofit,inparentheses, thenameoftheoriginalauthororpublisherofthatsectionifknown,orelseauniquenumber.Makethesameadjustmenttothesectiontitlesinthelistof InvariantSectionsinthelicensenoticeofthecombinedwork. Inthecombination,youmustcombineanysectionsEntitled"History"inthevariousoriginaldocuments,formingonesectionEntitled"History"likewise combineanysectionsEntitled"Acknowledgements",andanysectionsEntitled"Dedications".YoumustdeleteallsectionsEntitled"Endorsements".

6.COLLECTIONSOFDOCUMENTS
YoumaymakeacollectionconsistingoftheDocumentandotherdocumentsreleasedunderthisLicense,andreplacetheindividualcopiesofthisLicensein thevariousdocumentswithasinglecopythatisincludedinthecollection,providedthatyoufollowtherulesofthisLicenseforverbatimcopyingofeachofthe documentsinallotherrespects. Youmayextractasingledocumentfromsuchacollection,anddistributeitindividuallyunderthisLicense,providedyouinsertacopyofthisLicenseintothe extracteddocument,andfollowthisLicenseinallotherrespectsregardingverbatimcopyingofthatdocument.

7.AGGREGATIONWITHINDEPENDENTWORKS
AcompilationoftheDocumentoritsderivativeswithotherseparateandindependentdocumentsorworks,inoronavolumeofastorageordistribution medium,iscalledan"aggregate"ifthecopyrightresultingfromthecompilationisnotusedtolimitthelegalrightsofthecompilation'susersbeyondwhatthe individualworkspermit.WhentheDocumentisincludedinanaggregate,thisLicensedoesnotapplytotheotherworksintheaggregatewhicharenot themselvesderivativeworksoftheDocument. IftheCoverTextrequirementofsection3isapplicabletothesecopiesoftheDocument,theniftheDocumentislessthanonehalfoftheentireaggregate, theDocument'sCoverTextsmaybeplacedoncoversthatbrackettheDocumentwithintheaggregate,ortheelectronicequivalentofcoversiftheDocument isinelectronicform.Otherwisetheymustappearonprintedcoversthatbracketthewholeaggregate.

8.TRANSLATION
Translationisconsideredakindofmodification,soyoumaydistributetranslationsoftheDocumentunderthetermsofsection4.ReplacingInvariantSections withtranslationsrequiresspecialpermissionfromtheircopyrightholders,butyoumayincludetranslationsofsomeorallInvariantSectionsinadditiontothe originalversionsoftheseInvariantSections.YoumayincludeatranslationofthisLicense,andallthelicensenoticesintheDocument,andanyWarranty Disclaimers,providedthatyoualsoincludetheoriginalEnglishversionofthisLicenseandtheoriginalversionsofthosenoticesanddisclaimers.Incaseofa disagreementbetweenthetranslationandtheoriginalversionofthisLicenseoranoticeordisclaimer,theoriginalversionwillprevail. IfasectionintheDocumentisEntitled"Acknowledgements","Dedications",or"History",therequirement(section4)toPreserveitsTitle(section1)will typicallyrequirechangingtheactualtitle.

9.TERMINATION
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 97/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

Youmaynotcopy,modify,sublicense,ordistributetheDocumentexceptasexpresslyprovidedunderthisLicense.Anyattemptotherwisetocopy,modify, sublicense,ordistributeitisvoid,andwillautomaticallyterminateyourrightsunderthisLicense. However,ifyouceaseallviolationofthisLicense,thenyourlicensefromaparticularcopyrightholderisreinstated(a)provisionally,unlessanduntilthe copyrightholderexplicitlyandfinallyterminatesyourlicense,and(b)permanently,ifthecopyrightholderfailstonotifyyouoftheviolationbysomereasonable meanspriorto60daysafterthecessation. Moreover,yourlicensefromaparticularcopyrightholderisreinstatedpermanentlyifthecopyrightholdernotifiesyouoftheviolationbysomereasonable means,thisisthefirsttimeyouhavereceivednoticeofviolationofthisLicense(foranywork)fromthatcopyrightholder,andyoucuretheviolationpriorto30 daysafteryourreceiptofthenotice. TerminationofyourrightsunderthissectiondoesnotterminatethelicensesofpartieswhohavereceivedcopiesorrightsfromyouunderthisLicense.Ifyour rightshavebeenterminatedandnotpermanentlyreinstated,receiptofacopyofsomeorallofthesamematerialdoesnotgiveyouanyrightstouseit.

10.FUTUREREVISIONSOFTHISLICENSE
TheFreeSoftwareFoundationmaypublishnew,revisedversionsoftheGNUFreeDocumentationLicensefromtimetotime.Suchnewversionswillbe similarinspirittothepresentversion,butmaydifferindetailtoaddressnewproblemsorconcerns.Seehttp://www.gnu.org/copyleft/. EachversionoftheLicenseisgivenadistinguishingversionnumber.IftheDocumentspecifiesthataparticularnumberedversionofthisLicense"oranylater version"appliestoit,youhavetheoptionoffollowingthetermsandconditionseitherofthatspecifiedversionorofanylaterversionthathasbeenpublished (notasadraft)bytheFreeSoftwareFoundation.IftheDocumentdoesnotspecifyaversionnumberofthisLicense,youmaychooseanyversionever published(notasadraft)bytheFreeSoftwareFoundation.IftheDocumentspecifiesthataproxycandecidewhichfutureversionsofthisLicensecanbe used,thatproxy'spublicstatementofacceptanceofaversionpermanentlyauthorizesyoutochoosethatversionfortheDocument.

11.RELICENSING
"MassiveMultiauthorCollaborationSite"(or"MMCSite")meansanyWorldWideWebserverthatpublishescopyrightableworksandalsoprovidesprominent facilitiesforanybodytoeditthoseworks.Apublicwikithatanybodycaneditisanexampleofsuchaserver.A"MassiveMultiauthorCollaboration"(or"MMC") containedinthesitemeansanysetofcopyrightableworksthuspublishedontheMMCsite. "CCBYSA"meanstheCreativeCommonsAttributionShareAlike3.0licensepublishedbyCreativeCommonsCorporation,anotforprofitcorporationwitha principalplaceofbusinessinSanFrancisco,California,aswellasfuturecopyleftversionsofthatlicensepublishedbythatsameorganization. "Incorporate"meanstopublishorrepublishaDocument,inwholeorinpart,aspartofanotherDocument. AnMMCis"eligibleforrelicensing"ifitislicensedunderthisLicense,andifallworksthatwerefirstpublishedunderthisLicensesomewhereotherthanthis MMC,andsubsequentlyincorporatedinwholeorinpartintotheMMC,(1)hadnocovertextsorinvariantsections,and(2)werethusincorporatedpriorto November1,2008. TheoperatorofanMMCSitemayrepublishanMMCcontainedinthesiteunderCCBYSAonthesamesiteatanytimebeforeAugust1,2009,providedthe MMCiseligibleforrelicensing.

HowtousethisLicenseforyourdocuments
en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version 98/99

10/24/13

Non-Programmer's Tutorial for Python 2.6/Print version - Wikibooks, open books for an open world

TousethisLicenseinadocumentyouhavewritten,includeacopyoftheLicenseinthedocumentandputthefollowingcopyrightandlicensenoticesjust afterthetitlepage: Copyright(c)YEARYOURNAME. Permissionisgrantedtocopy,distributeand/ormodifythisdocument underthetermsoftheGNUFreeDocumentationLicense,Version1.3 oranylaterversionpublishedbytheFreeSoftwareFoundation withnoInvariantSections,noFrontCoverTexts,andnoBackCoverTexts. Acopyofthelicenseisincludedinthesectionentitled"GNU FreeDocumentationLicense". IfyouhaveInvariantSections,FrontCoverTextsandBackCoverTexts,replacethe"with...Texts."linewiththis: withtheInvariantSectionsbeingLISTTHEIRTITLES,withthe FrontCoverTextsbeingLIST,andwiththeBackCoverTextsbeingLIST. IfyouhaveInvariantSectionswithoutCoverTexts,orsomeothercombinationofthethree,mergethosetwoalternativestosuitthesituation. Ifyourdocumentcontainsnontrivialexamplesofprogramcode,werecommendreleasingtheseexamplesinparallelunderyourchoiceoffreesoftwarelicense, suchastheGNUGeneralPublicLicense,topermittheiruseinfreesoftware. Retrievedfrom"http://en.wikibooks.org/w/index.php?title=NonProgrammer%27s_Tutorial_for_Python_2.6/Print_version&oldid=2501137"
Thispagewaslastmodifiedon13March2013,at13:59. TextisavailableundertheCreativeCommonsAttribution/ShareAlikeLicenseadditionaltermsmayapply.Byusingthissite,youagreetotheTermsof UseandPrivacyPolicy.

en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/Print_version

99/99

Вам также может понравиться