non-programmers tutorial for pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf ·...

85
Non-Programmers Tutorial For Python Josh Cogliati November 20, 2001

Upload: phamlien

Post on 22-Apr-2018

245 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

Non-Programmers Tutorial For Python

Josh Cogliati

November20,2001

Page 2: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

Copyright(c) 1999-2001JoshCogliati.

Permissionis grantedto anyoneto make or distributeverbatimcopiesof this documentasreceived,in any medium,provided that the copyright noticeandpermissionnoticearepreserved,andthat the distributor grantsthe recipientpermissionfor furtherredistributionaspermittedby thisnotice.

Permissionis grantedto distributemodifiedversionsof thisdocument,or of portionsof it, undertheaboveconditions,providedalsothatthey carryprominentnoticesstatingwho lastalteredthem.

All examplepython sourcecodein this tutorial is grantedto the public domain. Thereforeyou may modify it andrelicenseit underany licenseyou please.

Page 3: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

Abstract

Non-ProgrammersTutorialFor Pythonis atutorialdesignedto beaintroductionto thePythonprogramminglanguage.Thisguideis for someonewith noprogrammingexperience.

If youhaveprogrammedin otherlanguagesI recommendusingThePythonTutorial writtenby GuidovanRossum.

This documentis availableasLATEX, HTML, PDF, andPostscript.Go to http://www.honors.montana.edu/˜jjc/easytut/to seeall theseforms.

If you have any questionsor commentspleasecontactme at [email protected] I welcomequestionsandcommentsaboutthis tutorial. I will try to answerany questionsyouhaveasbestasI can.

Thanksgo to JamesA. Brown for writing mostof the Windows install info. Thanksalsoto ElizabethCogliati forcomplainingenough:) abouttheoriginal tutorial,(thatis almostunusablefor anon-programmer)for proofreadingandfor many ideasandcommentson it. Thanksto JoeOppegaardfor writing all theexercises.Thanksto everyoneI havemissed.

Page 4: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

Dedicatedto ElizabethCogliati

Page 5: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

CONTENTS

1 Intr o 11.1 First thingsfirst . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.2 InstallingPython . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.3 InteractiveMode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.4 CreatingandRunningPrograms. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21.5 UsingPythonfrom thecommandline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

2 Hello, World 32.1 Whatyoushouldknow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32.2 Printing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32.3 Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42.4 Talking to humans(andotherintelligentbeings) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52.5 Examples. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

3 Who GoesThere? 93.1 InputandVariables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93.2 Examples. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

4 Count to 10 134.1 While loops. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134.2 Examples. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

5 Decisions 175.1 If statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175.2 Examples. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

6 Debugging 216.1 Whatis debugging? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216.2 Whatshouldtheprogramdo? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216.3 Whatdoestheprogramdo? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226.4 How do I fix theprogram?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

7 Defining Functions 277.1 CreatingFunctions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277.2 Examples. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31

i

Page 6: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

8 Lists 338.1 Variableswith morethanonevalue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338.2 More featuresof lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338.3 Examples. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

9 For Loops 41

10 BooleanExpressions 4510.1 Examples. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

11 Dictionaries 49

12 UsingModules 5512.1 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56

13 Mor eon Lists 57

14 Revengeof the Strings 6314.1 Examples. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67

15 File IO 6915.1 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73

16 Dealingwith the imperfect (or how to handleerrors) 7516.1 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76

17 The End 77

18 FAQ 79

Index 81

ii

Page 7: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

CHAPTER

ONE

Intro

1.1 First things first

So, you’ve never programmedbefore. As we go throughthis tutorial I will attemptto teachyou how to program.Therereally is only oneway to learnto program.You mustreadcodeandwrite code.I’m goingto show you lots ofcode.Youshouldtypein codethatI show youto seewhathappens.Playaroundwith it andmakechanges.Theworstthatcanhappenis thatit won’t work. WhenI typein codeit will beformattedlike this:

##Python is easy to learnprint "Hello, World!"

That’ssoit is easyto distinguishfrom theothertext. To make it confusingI will alsoprint whatthecomputeroutputsin thatsamefont.

Now, on to more important things. In order to programin Pythonyou needthe Pythonsoftware. If you don’talreadyhavethePythonsoftwaregoto http://www.python.org/download/andgettheproperversionfor yourplatform.Downloadit, readtheinstructionsandgetit installed.

1.2 Installing Python

Firstyouneedto downloadtheappropriatefile for yourcomputerfrom http://www.python.org/download. Go to the2.0link (or newer) andthengetthewindows installerif youuseWindowsor therpm or sourceif you useUnix.

TheWindowsinstallerwill downloadto file. Thefile canthenberunbydoubleclicking ontheiconthatis downloaded.Theinstallationwill thenproceed.

If yougettheUnix sourcemakesureyoucompilein thetk extensionif you wantto useIDLE.

1.3 Interactive Mode

Go into IDLE (alsocalledthePythonGUI). You shouldseeawindow thathassometext like this:

1

Page 8: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

Python 2.0 (#4, Dec 12 2000, 19:19:57)[GCC 2.95.2 20000220 (Debian GNU/Linux)] on linux2Type "copyright", "credits" or "license" for more information.IDLE 0.6 -- press F1 for help>>>

The>>> is Pythonway of telling you thatyou arein interactivemode.In interactivemodewhatyou typeis immedi-atelyrun. Try typing1+1 in. Pythonwill respondwith 2. Interactivemodeallowsyouto testoutandseewhatPythonwill do. If you ever feel you needto play with new Pythonstatementsgo into interactivemodeandtry themout.

1.4 Creating and Running Programs

Go into IDLE if you arenot already. Go to File thenNew Window. In this window typethefollowing:

print "Hello, World!"

First save theprogram.Go to File thenSave . Save it as‘ ’’hello.py’. (If you want you cansave it to someotherdirectorythanthedefault.) Now thatit is savedit canberun.

Next run the program by going to Edit then Run script . This will output Hello, World! on the*Python Shell* window.

1.5 Using Python from the command line

If you don’t want to usePythonfrom the commandline, you don’t have too, just useIDLE. To get into interactivemodejust type python with out any arguments.To run a programcreateit with a text editor (Emacshasa goodpythonmode)andthenrun it with python program name.

2 Chapter 1. Intro

Page 9: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

CHAPTER

TWO

Hello, World

2.1 What you should know

Youshouldknow how to editprogramsin atext editor, savethemto disk (floppy or hard)andrunthemoncethey havebeensaved.

2.2 Printing

Programmingtutorialssincethebeginningof timehavestartedwith a little programcalledHello, World! Sohereit is:

print "Hello, World!"

If youareusingthecommandline to runprogramsthentypeit in with a text editor, save it as‘hello.py’ andrun it with“python hello.py”

Otherwisego into IDLE, createa new window, andcreatetheprogramasin section1.4.

Whenthis programis runhere’swhatit prints:

Hello, World!

Now I’m notgoingto tell you thiseverytime,but whenI show youaprogramI recommendthatyou typeit in andrunit. I learnbetterwhenI typeit in andyouprobablydo too.

Now hereis amorecomplicatedprogram:

print "Jack and Jill went up a hill"print "to fetch a pail of water;"print "Jack fell down, and broke his crown,"print "and Jill came tumbling after."

Whenyou run thisprogramit printsout:

Jack and Jill went up a hillto fetch a pail of water;Jack fell down, and broke his crown,and Jill came tumbling after.

3

Page 10: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

Whenthecomputerrunsthis programit first seestheline:

print "Jack and Jill went up a hill"

sothecomputerprints:

Jack and Jill went up a hill

Thenthecomputergoesdown to thenext line andsees:

print "to fetch a pail of water;"

Sothecomputerprintsto thescreen:

to fetch a pail of water;

Thecomputerkeepslookingateachline, followsthecommandandthengoeson to thenext line. Thecomputerkeepsrunningcommandsuntil it reachestheendof theprogram.

2.3 Expressions

Hereis anotherprogram:

print "2 + 2 is", 2+2print "3 * 4 is", 3 * 4print 100 - 1, " = 100 - 1"print "(33 + 2) / 5 + 11.5 = ",(33 + 2) / 5 + 11.5

And hereis theoutputwhentheprogramis run:

2 + 2 is 43 * 4 is 1299 = 100 - 1(33 + 2) / 5 + 11.5 = 18.5

As youcanseePythoncanturn your thousanddollarcomputerinto a5 dollarcalculator.

Pythonhassix basicoperations:

Operation Symbol ExampleExponentiation ** 5 ** 2 == 25Multiplication * 2 * 3 == 6Division / 14 / 3 == 4Remainder % 14 % 3 == 2Addition + 1 + 2 == 3Subtraction - 4 - 3 == 1

Noticethatdivisionfollowstherule, if therearenodecimalsto startwith, therewill benodecimalsto endwith. (Note:Thiswill bechangingin Python2.3)Thefollowing programshowsthis:

4 Chapter 2. Hello, World

Page 11: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

print "14 / 3 = ",14 / 3print "14 % 3 = ",14 % 3printprint "14.0 / 3.0 =",14.0 / 3.0print "14.0 % 3.0 =",14 % 3.0printprint "14.0 / 3 =",14.0 / 3print "14.0 % 3 =",14.0 % 3printprint "14 / 3.0 =",14 / 3.0print "14 % 3.0 =",14 % 3.0print

With theoutput:

14 / 3 = 414 % 3 = 2

14.0 / 3.0 = 4.6666666666714.0 % 3.0 = 2.0

14.0 / 3 = 4.6666666666714.0 % 3 = 2.0

14 / 3.0 = 4.6666666666714 % 3.0 = 2.0

Noticehow Pythongivesdifferentanswersfor someproblemsdependingon whetheror not theredecimalvaluesareused.

Theorderof operationsis thesameasin math:

1. parentheses()

2. exponents**

3. multiplication* , division \ , andremainder%

4. addition+ andsubtraction-

2.4 Talking to humans (and other intelligent beings)

Often in programmingyou are doing somethingcomplicatedand may not in the future rememberwhat you did.Whenthis happenstheprogramshouldprobablybecommented.A commentis a noteto you andotherprogrammersexplainingwhatis happening.For example:

#Not quite PI, but an incredible simulationprint 22.0/7.0

Noticethat thecommentstartswith a #. Commentsareusedto communicatewith otherswho readtheprogramandyour futureself to makeclearwhatis complicated.

2.4. Talking to humans (and other intelligent beings) 5

Page 12: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

2.5 Examples

Eachchapter(eventually)will containexamplesof theprogrammingfeaturesintroducedin thechapter. Youshouldatleastlook over themseeif you understandthem. If you don’t, you maywant to type themin andseewhathappens.Messaroundthem,changethemandseewhathappens.

Denmark.py

print "Something’s rotten in the state of Denmark."print " -- Shakespeare"

Output:

Something’s rotten in the state of Denmark.-- Shakespeare

School.py

#This is not quite true outside of USA# and is based on my dim memories of my younger yearsprint "Firstish Grade"print "1+1 =",1+1print "2+4 =",2+4print "5-2 =",5-2printprint "Thirdish Grade"print "243-23 =",243-23print "12*4 =",12*4print "12/3 =",12/3print "13/3 =",13/3," R ",13%3printprint "Junior High"print "123.56-62.12 =",123.56-62.12print "(4+3)*2 =",(4+3)*2print "4+3*2 =",4+3*2print "3**2 =",3**2print

Output:

6 Chapter 2. Hello, World

Page 13: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

Firstish Grade1+1 = 22+4 = 65-2 = 3

Thirdish Grade243-23 = 22012*4 = 4812/3 = 413/3 = 4 R 1

Junior High123.56-62.12 = 61.44(4+3)*2 = 144+3*2 = 103**2 = 9

2.6 Exercises

Write aprogramthatprintsyour full nameandyourbirthdayasseparatestrings.

Write aprogramthatshows theuseof all 6 mathfunctions.

2.6. Exercises 7

Page 14: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

8

Page 15: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

CHAPTER

THREE

Who Goes There?

3.1 Input and Variables

Now I feel it is time for a really complicatedprogram.Hereit is:

print "Halt!"s = raw_input("Who Goes there? ")print "You may pass,", s

WhenI ranit hereis whatmy screenshowed:

Halt!Who Goes there? JoshYou may pass, Josh

Of coursewhenyou run the programyour screenwill look differentbecauseof the raw_input statement.Whenyou rantheprogramyou probablynoticed(you did run theprogram,right?) how you hadto type in your nameandthenpressEnter. Thentheprogramprintedout somemoretext andalsoyour name.This is anexampleof input. Theprogramreachesacertainpointandthenwaitsfor theuserto input somedatathattheprogramcanuselater.

Of course,gettinginformationfrom theuserwould beuselessif we didn’t haveanywhereto put thatinformationandthis is wherevariablescomein. In thepreviousprograms is a variable.Variablesarelike a box thatcanstoresomepieceof data.Hereis aprogramto show examplesof variables:

a = 123.4b23 = ’Spam’first_name = "Bill"b = 432c = a + bprint "a + b is", cprint "first_name is", first_nameprint "Sorted Parts, After Midnight or",b23

And hereis theoutput:

a + b is 555.4first_name is BillSorted Parts, After Midnight or Spam

9

Page 16: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

Variablesstoredata.Thevariablesin theabove programarea, b23 , first_name , b, andc . Thetwo basictypesarestringsandnumbers.Stringsarea sequenceof letters,numbersandothercharacters.In this exampleb23 andfirst_name arevariablesthatarestoringstrings.Spam, Bill , a + b is , andfirst_name is arethestringsin this program.Thecharactersaresurroundedby " or ’ . Theothertypeof variablesarenumbers.

Okay, sowehavetheseboxescalledvariablesandalsodatathatcango into thevariable.Thecomputerwill seea linelike first_name = "Bill" andit readsit asPutthestringBill into thebox(or variable)first_name . Lateron it seesthestatementc = a + b andit readsit asPuta + b or 123.4 + 432 or 555.4 into c .

Hereis anotherexampleof variableusage:

a = 1print aa = a + 1print aa = a * 2print a

And of coursehereis theoutput:

124

Evenif it is thesamevariableon bothsidesthecomputerstill readsit as:First find out thedatato storeandthanfindout wherethedatagoes.

OnemoreprogrambeforeI endthis chapter:

num = input("Type in a Number: ")str = raw_input("Type in a String: ")print "num =", numprint "num is a ",type(num)print "num * 2 =",num*2print "str =", strprint "str is a ",type(str)print "str * 2 =",str*2

TheoutputI got was:

Type in a Number: 12.34Type in a String: Hellonum = 12.34num is a <type ’float’>num * 2 = 24.68str = Hellostr is a <type ’string’>str * 2 = HelloHello

Notice that num wasgottenwith input while str wasgottenwith raw_input . raw_input returnsa stringwhile input returnsa number. Whenyou want theuserto typein a numberuseinput but if you want theusertotypein a stringuseraw_input .

Thesecondhalf of theprogramusestype whichtellswhatavariableis. Numbersareof type int or float (which

10 Chapter 3. Who Goes There?

Page 17: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

are short for ’integer’ and ’floating point’ respectively). Stringsare of type string . Integersand floats can beworkedon by mathematicalfunctions,stringscannot.Noticehow whenpythonmultiplesa numberby a integer theexpectedthing happens.Howeverwhena string is multiplied by a integerthestringhasthatmany copiesof it addedi.e. str * 2 = HelloHello .

3.2 Examples

Rate times.py

#This programs calculates rate and distance problemsprint "Input a rate and a distance"rate = input("Rate:")distance = input("Distance:")print "Time:",distance/rate

Sampleruns:

> python rate_times.pyInput a rate and a distanceRate:5Distance:10Time: 2> python rate_times.pyInput a rate and a distanceRate:3.52Distance:45.6Time: 12.9545454545

Area.py

#This program calculates the perimeter and area of a rectangleprint "Calculate information about a rectangle"length = input("Length:")width = input("Width:")print "Area",length*widthprint "Perimeter",2*length+2*width

Sampleruns:

> python area.pyCalculate information about a rectangleLength:4Width:3Area 12Perimeter 14> python area.pyCalculate information about a rectangleLength:2.53Width:5.2Area 13.156Perimeter 15.46

3.2. Examples 11

Page 18: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

temperature.py

#Converts fahrenheit to celciustemp = input("Farenheit temperature:")print (temp-32.0)*5.0/9.0

Sampleruns:

> python temperature.pyFarenheit temperature:320.0> python temperature.pyFarenheit temperature:-40-40.0> python temperature.pyFarenheit temperature:212100.0> python temperature.pyFarenheit temperature:98.637.0

3.3 Exercises

Write a programthatgets2 stringvariablesand2 integervariablesfrom the user, concatenates(joins themtogetherwith no spaces)anddisplaysthestrings,thenmultipliesthetwo numberson anew line.

12 Chapter 3. Who Goes There?

Page 19: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

CHAPTER

FOUR

Count to 10

4.1 While loops

Presentingour first controlstructure.Ordinarily thecomputerstartswith thefirst line andthengoesdown from there.Controlstructureschangetheorderthatstatementsareexecutedor decideif acertainstatementwill berun. Here’s thesourcefor a programthatusesthewhile controlstructure:

a = 0while a < 10:

a = a + 1print a

And hereis theextremelyexciting output:

12345678910

(And you thoughtit couldn’t getany worseafter turningyour computerinto a five dollar calculator?)Sowhatdoestheprogramdo?First it seestheline a = 0 andmakesa zero.Thenit seeswhile a < 10: andsothecomputerchecksto seeif a < 10 . Thefirst time thecomputerseesthis statementa is zerosoit is lessthan10. In otherwordswhile a is lessthantenthecomputerwill run thetabbedin statements.

Hereis anotherexampleof theuseof while :

13

Page 20: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

a = 1s = 0print ’Enter Numbers to add to the sum.’print ’Enter 0 to quit.’while a != 0 :

print ’Current Sum:’,sa = input(’Number? ’)s = s + a

print ’Total Sum =’,s

Thefirst time I ranthis programPythonspit out this:

File "sum.py", line 3while a != 0

ˆSyntaxError: invalid syntax

I hadforgottento put the : afterthewhile. Theerrormessagecomplainedaboutthatproblemandpointedout whereit thoughttheproblemwaswith theˆ . After theproblemwasfixedherewaswhatI did with theprogram:

Enter Numbers to add to the sum.Enter 0 to quit.Current Sum: 0Number? 200Current Sum: 200Number? -15.25Current Sum: 184.75Number? -151.85Current Sum: 32.9Number? 10.00Current Sum: 42.9Number? 0Total Sum = 42.9

Noticehow print ’Total Sum =’,s is only runat theend.Thewhile statementonly affectstheline thataretabbedin (a.k.a.indented).The!= meansdoesnotequalsowhile a != 0 : meansuntil a is zerorun thetabbedin statementsthatareafterwards.

Now thatwe have while loops,it is possibleto have programsthat run forever. An easyway to do this is to write aprogramlike this:

while 1 == 1:print "Help, I’m stuck in a loop."

This programwill outputHelp, I’m stuck in a loop. until the heatdeathof the universeor you stopit.Theway to stopit is to hit theControl(or Ctrl) buttonand‘c’ (theletter)at thesametime. Thiswill kill theprogram.(Note: sometimesyouwill have to hit enteraftertheControlC.)

4.2 Examples

Fibonnaci.py

14 Chapter 4. Count to 10

Page 21: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

#This program calulates the fibonnaci sequencea = 0b = 1count = 0max_count = 20while count < max_count:

count = count + 1#we need to keep track of a since we change itold_a = aa = bb = old_a + b#Notice that the , at the end of a print statement keeps it# from switching to a new lineprint old_a,

print

Output:

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181

Password.py

# Waits until a password has been entered. Use control-C to break out with out# the password

password = "foobar"

#note that != means not equalwhile password != "unicorn":

password = raw_input("Password:")print "Welcome in"

Samplerun:

Password:auoPassword:y22Password:passwordPassword:open sesamePassword:unicornWelcome in

4.2. Examples 15

Page 22: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

16

Page 23: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

CHAPTER

FIVE

Decisions

5.1 If statement

As alwaysI believe I shouldstarteachchapterwith a warmup typing exercisesohereis a shortprogramto computetheabsolutevalueof a number:

n = input("Number? ")if n < 0:

print "The absolute value of",n,"is",-nelse:

print "The absolute value of",n,"is",n

Hereis theoutputfrom thetwo timesthatI ranthis program:

Number? -34The absolute value of -34 is 34

Number? 1The absolute value of 1 is 1

Sowhatdoesthecomputerdo whenwhenit seesthis pieceof code?First it promptstheuserfor a numberwith thestatementn = input("Number? ") . Next it readsthe line if n < 0: If n is lessthanzeroPythonrunsthe line print "The absolute value of",n,"is",-n . Otherwisepython runs the line print "Theabsolute value of",n,"is",n .

More formally Pythonlooksat whethertheexpression n < 0 is trueor false.A if statementis followedby a blockof statementsthatarerun whenthe expressionis true. Optionally after the if statementis a else statement.Theelse statementis run if theexpressionis false.

Thereareseveraldifferentteststhata expressioncanhave. Hereis a tableof all of them:

operator function< lessthan<= lessthanor equalto> greaterthan>= greaterthanor equalto== equal!= not equal<> anotherway to saynot equal

Anotherfeatureof theif commandis theelif statement.It standsfor elseif andmeansif theoriginal if statement

17

Page 24: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

is falseandthentheelif partis truedo thatpart.Here’sa example:

a = 0while a < 10:

a = a + 1if a > 5:

print a," > ",5elif a <= 7:

print a," <= ",7else:

print "Neither test was true"

andtheoutput:

1 <= 72 <= 73 <= 74 <= 75 <= 76 > 57 > 58 > 59 > 510 > 5

Noticehow theelif a <= 7 is only testedwhenthe if statementfail to betrue.elif allowsmultiple teststo bedonein a singleif statement.

5.2 Examples

High low.py

#Plays the guessing game higher or lower# (originally written by Josh Cogliati, improved by Quique)

#This should actually be something that is semi random like the# last digits of the time or something else, but that will have to# wait till a later chapter. (Extra Credit, modify it to be random# after the Modules chapter)number = 78guess = 0

while guess != number :guess = input ("Guess a number: ")

if guess > number :print "Too high"

elif guess < number :print "Too low"

print "Just right"

18 Chapter 5. Decisions

Page 25: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

Samplerun:

Guess a number:100Too highGuess a number:50Too lowGuess a number:75Too lowGuess a number:87Too highGuess a number:81Too highGuess a number:78Just right

5.3 Exercises

Write aprogramthathasa userguessyourname,but they only get3 chancesto dosountil theprogramquits.

Write a programthataskstheusertheir name,if they enteryour namesay”That is a nicename”,if they enter”JohnCleese”or ”Michael Palin”, tell themhow you feelaboutthem;), otherwisetell them”Youhaveanicename”.

5.3. Exercises 19

Page 26: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

20

Page 27: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

CHAPTER

SIX

Debugging

6.1 What is debugging?

As soonaswe startedprogramming,we foundto our surprisethat it wasn’t aseasyto getprogramsright as we had thought. Debugging had to be discovered. I can rememberthe exact instantwhen Irealizedthat a large part of my life from thenon wasgoing to be spentin finding mistakesin my ownprograms.

– MauriceWilkesdiscoversdebugging,1949

By now if you have beenmessingaroundwith the programsyou have probablyfound that sometimesthe programdoessomethingyou didn’t want it to do. This is fairly common.Debuggingis the processof figuring out what thecomputeris doing andthengettingit to do what you want it to do. This canbe tricky. I oncespentnearlya weektrackingdown andfixing a bug thatwascausedby someoneputtinganx wherea y shouldhavebeen.

Thischapterwill bemoreabstractthanpreviouschapters.Pleasetell meif it is useful.

6.2 What should the program do?

Thefirst thing to do (this soundsobvious)is to figureout whattheprogramshouldbedoingif it is runningcorrectly.Comeupwith sometestcasesandseewhathappens.For example,let’ssayI haveaprogramto computetheperimeterof a rectangle(thesumof thelengthof all theedges).I have thefollowing testcases:

width height perimeter3 4 142 3 104 4 162 2 85 1 12

I now run my programon all of the testcasesandseeif theprogramdoeswhat I expectit to do. If it doesn’t thenIneedto find out whatthecomputeris doing.

More commonlysomeof thetestcaseswill work andsomewill not. If that is thecaseyou shouldtry andfigureoutwhat theworking oneshave in common.For examplehereis theoutputfor a perimeterprogram(you get to seethecodein aminute):

Height: 3Width: 4perimeter = 15

21

Page 28: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

Height: 2Width: 3perimeter = 11

Height: 4Width: 4perimeter = 16

Height: 2Width: 2perimeter = 8

Height: 5Width: 1perimeter = 8

Noticethatit didn’t work for thefirst two inputs,it workedfor thenext two andit didn’t work on thelastone.Try andfigureout whatis in commonwith theworking ones.Onceyouhavesomeideawhattheproblemis finding thecauseis easier. With yourown programsyoushouldtry moretestcasesif you needthem.

6.3 What does the program do?

The next thing to do is to look at the sourcecode. Oneof the most importantthings to do while programmingisreadingsourcecode.Theprimaryway to do this is codewalkthroughs.

A codewalkthroughstartsat thefirst line, andworks its way down until theprogramis done.While loopsandifstatementsmeanthat somelines may never be run andsomelines arerun many times. At eachline you figure outwhatPythonhasdone.

Letsstartwith thesimpleperimeterprogram.Don’t typeit in, youaregoingto readit, not run it. Thesourcecodeis:

height = input("Height: ")width = input("Width: ")print "perimeter = ",width+height+width+width

Question: Whatis thefirst line Pythonruns?

Answer: Thefirst line is alway runfirst. In this caseit is: height = input("Height: ")

Question: Whatdoesthatline do?

Answer: PrintsHeight: , waitsfor theuserto typeanumberin, andputsthatin thevariableheight.

Question: Whatis thenext line thatruns?

Answer: In general,it is thenext line down which is: width = input("Width: ")

Question: Whatdoesthatline do?

Answer: PrintsWidth: , waitsfor theuserto typeanumberin, andputswhattheusertypesin thevariablewidth.

Question: Whatis thenext line thatruns?

22 Chapter 6. Debugging

Page 29: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

Answer: Whenthenext line is not indentedmoreor lessthanthecurrentline, it is the line right afterwards,so it is:print "perimeter = ",width+height+width+width (It mayalsoruna functionin thecurrentline, butthatsa futurechapter.)

Question: Whatdoesthatline do?

Answer: First it printsperimeter =, thenit printswidth+height+width+width .

Question: Doeswidth+height+width+width calculatetheperimeterproperly?

Answer: Let’s see,perimeterof a rectangleis thebottom(width) plustheleft side(height)plus thetop (width) plustheright side(huh?).Thelastitem shouldbetheright side’s length,or theheight.

Question: Do youunderstandwhy someof thetimestheperimeterwascalculated‘correctly’?

Answer: It wascalculatedcorrectlywhenthewidth andtheheightwereequal.

Thenext programwe will do a codewalkthroughfor is a programthat is supposedto print out 5 dotson thescreen.However, this is whattheprogramis outputting:

. . . .

And hereis theprogram:

number = 5while number > 1:

print ".",number = number - 1

print

This programwill bemorecomplex to walkthroughsinceit now hasindentedportions(or controlstructures).Let usbegin.

Question: Whatis thefirst line to berun?

Answer: Thefirst line of thefile: number = 5

Question: Whatdoesit do?

Answer: Putsthenumber5 in thevariablenumber.

Question: Whatis thenext line?

Answer: Thenext line is: while number > 1:

Question: Whatdoesit do?

Answer: Well, while statementsin generallook at their expression,andif it is truethey do thenext indentedblockof code,otherwisethey skip thenext indentedblockof code.

Question: Sowhatdoesit do right now?

Answer: If number > 1 is truethenthenext two lineswill berun.

Question: Sois number > 1?

Answer: Thelastvalueput into number was5 and5 > 1 soyes.

Question: Sowhatis thenext line?

Answer: Sincethewhile wastruethenext line is: print ".",

Question: Whatdoesthatline do?

Answer: Printsonedotandsincethestatementendswith a , thenext print statementwill notbeonadifferentscreen

6.3. What does the program do? 23

Page 30: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

line.

Question: Whatis thenext line?

Answer: number = number - 1 sincethatis following line andthereareno indentchanges.

Question: Whatdoesit do?

Answer: It calculatesnumber - 1, which is thecurrentvalueof number (or 5) subtracts1 from it, andmakesthatthenew valueof number. Sobasicallyit changesnumber ’svaluefrom 5 to 4.

Question: Whatis thenext line?

Answer: Well, theindentlevel decreasessowehaveto look atwhattypeof controlstructureit is. It is awhile loop,sowehave to go backto thewhile clausewhich is while number > 1:

Question: Whatdoesit do?

Answer: It looksat thevalueof number, which is 4, andcomparesit to 1 andsince4 > 1 thewhile loopcontinues.

Question: Whatis thenext line?

Answer: Sincethewhile loopwastrue,thenext line is: print ".",

Question: Whatdoesit do?

Answer: It printsaseconddot on theline.

Question: Whatis thenext line?

Answer: No indentchangesoit is: number = number - 1

Question: And whatdoesit do?

Answer: It talksthecurrentvalueof number(4), subtracts1 from it, whichgivesit 3 andthenfinally makes3 thenewvalueof number.

Question: Whatis thenext line?

Answer: Sincethereis anindentchangecausedby theendof thewhile loop,thenext line is: while number > 1:

Question: Whatdoesit do?

Answer: It comparesthecurrentvalueof number(3) to 1. 3 > 1 sothewhile loop continues.

Question: Whatis thenext line?

Answer: Sincethewhile loopconditionwastruethenext line is: print ".",

Question: And it doeswhat?

Answer: A third dot is printedon theline.

Question: Whatis thenext line?

Answer: It is: number = number - 1

Question: Whatdoesit do?

Answer: It takesthecurrentvalueof number(3) subtractsfrom it 1 andmakesthe2 thenew valueof number.

Question: Whatis thenext line?

Answer: Backup to thestartof thewhile loop: while number > 1:

Question: Whatdoesit do?

Answer: It comparesthecurrentvalueof number(2) to 1. Since2 > 1 thewhile loopcontinues.

Question: Whatis thenext line?

Answer: Sincethewhile loop is continuing:print ".",

24 Chapter 6. Debugging

Page 31: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

Question: Whatdoesit do?

Answer: It discoversthe meaningof life, the universeandeverything. I’m joking. (I hadto make sureyou wereawake.) Theline printsa fourth doton thescreen.

Question: Whatis thenext line?

Answer: It’ s: number = number - 1

Question: Whatdoesit do?

Answer: Takesthecurrentvalueof number(2) subtracts1 andmakes1 thenew valueof number.

Question: Whatis thenext line?

Answer: Backup to thewhile loop: while number > 1:

Question: Whatdoestheline do?

Answer: It comparesthe currentvalueof number(1) to 1. Since1 > 1 is false(oneis not greaterthanone),thewhile loop exits.

Question: Whatis thenext line?

Answer: Sincethewhile loopconditionwasfalsethenext line is theline afterthewhile loop exits, or: print

Question: Whatdoesthatline do?

Answer: Makesthescreengo to thenext line.

Question: Why doesn’t theprogramprint 5 dots?

Answer: Theloop exits 1 dot too soon.

Question: How canwefix that?

Answer: Make theloopexit 1 dot later.

Question: And how do wedo that?

Answer: Thereareseveralways.Oneway would beto changethewhile loop to: while number > 0: Anotherwaywould beto changetheconditionalto: number >= 1 Therearea coupleothers.

6.4 How do I fix the program?

Youneedto figureoutwhattheprogramis doing.Youneedto figureoutwhattheprogramshoulddo. Figureoutwhatthedifferencebetweenthetwo is. Debuggingis askill thathasto bedoneto belearned.If youcan’t figureit outafteranhouror sotake a break,talk to someoneabouttheproblemor contemplatethe lint in your navel. Comebackin awhile andyouwill probablyhavenew ideasabouttheproblem.Goodluck.

6.4. How do I fix the program? 25

Page 32: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

26

Page 33: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

CHAPTER

SEVEN

Defining Functions

7.1 Creating Functions

To startoff thischapterI amgoingto giveyouaexampleof whatyou coulddo but shouldn’t (sodon’t typeit in):

a = 23b = -23

if a < 0:a = -a

if b < 0:b = -b

if a == b:print "The absolute values of", a,"and",b,"are equal"

else:print "The absolute values of a and b are different"

with theoutputbeing:

The absolute values of 23 and 23 are equal

Theprogramseemsalittle repetitive. (Programmershateto repeatthings(That’swhatcomputersarefor aren’t they?))FortunatelyPythonallowsyou to createfunctionsto removeduplication.Here’s therewrittenexample:

a = 23b = -23

def abs(num):if num < 0:

num = -numreturn num

if abs(a) == abs(b):print "The absolute values of", a,"and",b,"are equal"

else:print "The absolute values of a and b are different"

with theoutputbeing:

27

Page 34: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

The absolute values of 23 and -23 are equal

The key featureof this programis the def statement.def (short for define)startsa function definition. def isfollowedby thenameof thefunctionabs . Next comesa ( followedby theparameternum (num is passedfrom theprogramfrom wherever it is calledto thefunction).Thestatementsafterthe: areexecutedwhenthefunctionis used.Thestatementscontinueuntil eitherthe indentedstatementsendor a returnis encountered.The return statementreturnsa valuebackto theplacewherethefunctionwascalled.

Noticehow thevaluesof a andb arenot changed.Functionsof coursecanbeusedto repeattasksthatdon’t returnvalues.Here’ssomeexamples:

def hello():print "Hello"

def area(width,height):return width*height

def print_welcome(name):print "Welcome",name

hello()hello()

print_welcome("Fred")w = 4h = 5print "width =",w,"height =",h,"area =",area(w,h)

with outputbeing:

HelloHelloWelcome Fredwidth = 4 height = 5 area = 20

Thatexamplejustshowssomemorestuff thatyoucandowith functions.Noticethatyoucanusenoargumentsor twoor more.Noticealsohow a returnis optional.

Functionscanbeusedto eliminaterepeatcode.

7.2 Examples

factorial.py

28 Chapter 7. Defining Functions

Page 35: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

#defines a function that calculates the factorial

def factorial(n):if n <= 1:

return 1return n*factorial(n-1)

print "2! = ",factorial(2)print "3! = ",factorial(3)print "4! = ",factorial(4)print "5! = ",factorial(5)

Output:

2! = 23! = 64! = 245! = 120

temperature2.py

#converts temperature to fahrenheit or celsius

def print_options():print "Options:"print " ’p’ print options"print " ’c’ convert from celsius"print " ’f’ convert from fahrenheit"print " ’q’ quit the program"

def celsius_to_fahrenheit(c_temp):return 9.0/5.0*c_temp+32

def fahrenheit_to_celsius(f_temp):return (f_temp - 32.0)*5.0/9.0

choice = "p"while choice != "q":

if choice == "c":temp = input("Celsius temperature:")print "Fahrenheit:",celsius_to_fahrenheit(te mp)

elif choice == "f":temp = input("Fahrenheit temperature:")print "Celsius:",fahrenheit_to_celsius(temp)

elif choice != "q":print_options()

choice = raw_input("option:")

SampleRun:

7.2. Examples 29

Page 36: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

> python temperature2.pyOptions:

’p’ print options’c’ convert from celsius’f’ convert from fahrenheit’q’ quit the program

option:cCelsius temperature:30Fahrenheit: 86.0option:fFahrenheit temperature:60Celsius: 15.5555555556option:q

area2.py

#By Amos Satterleeprintdef hello():

print ’Hello!’

def area(width,height):return width*height

def print_welcome(name):print ’Welcome,’,name

name = raw_input(’Your Name: ’)hello(),print_welcome(name)printprint ’To find the area of a rectangle,’print ’Enter the width and height below.’printw = input(’Width: ’)while w <= 0:

print ’Must be a positive number’w = input(’Width: ’)

h = input(’Height: ’)while h <= 0:

print ’Must be a positive number’h = input(’Height: ’)

print ’Width =’,w,’ Height =’,h,’ so Area =’,area(w,h)

SampleRun:

30 Chapter 7. Defining Functions

Page 37: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

Your Name: JoshHello!Welcome, Josh

To find the area of a rectangle,Enter the width and height below.

Width: -4Must be a positive numberWidth: 4Height: 3Width = 4 Height = 3 so Area = 12

7.3 Exercises

Rewrite thearea.py programdonein 3.2 to have a separatefunction for theareaof a square,theareaof a rectangle,andtheareaof acircle. (3.14* radius**2). Thisprogramshouldincludeamenuinterface.

7.3. Exercises 31

Page 38: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

32

Page 39: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

CHAPTER

EIGHT

Lists

8.1 Variables with more than one value

You have alreadyseenordinaryvariablesthatstorea singlevalue. However othervariabletypescanhold morethanonevalue.Thesimplesttypeis calleda list. Hereis a exampleof a list beingused:

which_one = input("What month (1-12)? ")months = [’January’, ’February’, ’March’, ’April’, ’May’, ’June’, ’July’,\’August’, ’September’, ’October’, ’November’, ’December’]if 1 <= which_one <= 12:

print "The month is",months[which_one - 1]

andaoutputexample:

What month (1-12)? 3The month is March

In this examplethe months is a list. months is definedwith the lines months = [’January’, ’Febru-ary’, ’March’, ’April’, ’May’, ’June’, ’July’,\ ’August’, ’September’, ’Octo-ber’, ’November’, ’December’] (Note that a \ canbe usedto split a long line). The [ and ] startandendthe list with comma’s (“ , ”) separatingthe list items. The list is usedin months[which_one - 1] . A listconsistsof itemsthatarenumberedstartingat 0. In otherwordsif you wantedJanuaryyou would usemonths[0] .Givea list anumberandit will returnthevaluethatis storedat thatlocation.

Thestatementif 1 <= which one <= 12: will only betrueif which one is betweenoneandtwelve inclu-sive (in otherwordsit is whatyouwouldexpectif youhaveseenthatin algebra).

Lists can be thoughtof as a seriesof boxes. For example,the boxescreatedby demolist = [’life’,42,’the universe’, 6,’and’,7] would look like this:

boxnumber 0 1 2 3 4 5demolist ‘life’ 42 ‘the universe’ 6 ‘and’ 7

Eachbox is referencedby its numberso thestatementdemolist[0] would get ’life’ , demolist[1] wouldget42 andsoon up to demolist[5] getting7.

8.2 More features of lists

The next exampleis just to show a lot of otherstuff lists cando (for onceI don’t expectyou to type it in, but youshouldprobablyplay aroundwith lists until youarecomfortablewith them.).Heregoes:

33

Page 40: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

demolist = [’life’,42, ’the universe’, 6,’and’,7]print ’demolist = ’,demolistdemolist.append(’everything’)print "after ’everything’ was appended demolist is now:"print demolistprint ’len(demolist) =’, len(demolist)print ’demolist.index(42) =’,demolist.index(42)print ’demolist[1] =’, demolist[1]#Next we will loop through the listc = 0while c < len(demolist):

print ’demolist[’,c,’]=’,demolist[c]c = c + 1

del demolist[2]print "After ’the universe’ was removed demolist is now:"print demolistif ’life’ in demolist:

print "’life’ was found in demolist"else:

print "’life’ was not found in demolist"if ’amoeba’ in demolist:

print "’amoeba’ was found in demolist"if ’amoeba’ not in demolist:

print "’amoeba’ was not found in demolist"demolist.sort()print ’The sorted demolist is ’,demolist

Theoutputis:

demolist = [’life’, 42, ’the universe’, 6, ’and’, 7]after ’everything’ was appended demolist is now:[’life’, 42, ’the universe’, 6, ’and’, 7, ’everything’]len(demolist) = 7demolist.index(42) = 1demolist[1] = 42demolist[ 0 ]= lifedemolist[ 1 ]= 42demolist[ 2 ]= the universedemolist[ 3 ]= 6demolist[ 4 ]= anddemolist[ 5 ]= 7demolist[ 6 ]= everythingAfter ’the universe’ was removed demolist is now:[’life’, 42, 6, ’and’, 7, ’everything’]’life’ was found in demolist’amoeba’ was not found in demolistThe sorted demolist is [6, 7, 42, ’and’, ’everything’, ’life’]

This exampleusesa wholebunchof new functions.Noticethatyou canjust print a wholelist. Next theappendfunctionis usedto addanew itemto theendof thelist. len returnshow many itemsarein alist. Thevalid indexes(asin numbersthatcanbeusedinsideof the[]) of alist rangefrom 0 to len - 1. Theindex functiontell wherethefirstlocationof anitem is locatedin a list. Noticehow demolist.index(42) returns1 andwhendemolist[1] isrun it returns42. Theline #Next we will loop through the list is a justa reminderto theprogrammer(alsocalleda comment).Pythonwill ignoreany linesthatstartwith a #. Next thelines:

34 Chapter 8. Lists

Page 41: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

c = 0while c < len(demolist):

print ’demolist[’,c,’]=’,demolist[c]c = c + 1

Createavariablec whichstartsat0 andis incrementeduntil it reachesthelastindex of thelist. Meanwhiletheprintstatementprintsout eachelementof thelist.

Thedel commandcanbeusedto removeagivenelementin a list. Thenext few linesusethe in operatorto testif aelementis in or is not in a list.

Thesort functionsortsthelist. This is usefulif youneeda list in orderfrom smallestnumberto largestor alphabet-ical. Notethatthis rearrangesthelist.

In summaryfor a list thefollowing operationsoccur:

example explanationlist[2] accessestheelementat index 2list[2] = 3 setstheelementat index 2 to be3del list[2] removestheelementat index 2len(list) returnsthelengthof list"value" in list is trueif "value" is anelementin list"value" not in list is trueif "value" is not anelementin listlist.sort() sortslistlist.index("value") returnstheindex of thefirst placethat"value" occurslist.append("value") addsanelement"value" at theendof thelist

Thisnext exampleusesthesefeaturesin amoreusefulway:

8.2. More features of lists 35

Page 42: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

menu_item = 0list = []while menu_item != 9:

print "--------------------"print "1. Print the list"print "2. Add a name to the list"print "3. Remove a name from the list"print "4. Change an item in the list"print "9. Quit"menu_item = input("Pick an item from the menu: ")if menu_item == 1:

current = 0if len(list) > 0:

while current < len(list):print current,". ",list[current]current = current + 1

else:print "List is empty"

elif menu_item == 2:name = raw_input("Type in a name to add: ")list.append(name)

elif menu_item == 3:del_name = raw_input("What name would you like to remove: ")if del_name in list:

item_number = list.index(del_name)del list[item_number]

else:print del_name," was not found"

elif menu_item == 4:old_name = raw_input("What name would you like to change: ")if old_name in list:

item_number = list.index(old_name)new_name = raw_input("What is the new name: ")list[item_number] = new_name

else:print old_name," was not found"

print "Goodbye"

And hereis partof theoutput:

36 Chapter 8. Lists

Page 43: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

--------------------1. Print the list2. Add a name to the list3. Remove a name from the list4. Change an item in the list9. Quit

Pick an item from the menu: 2Type in a name to add: Jack

Pick an item from the menu: 2Type in a name to add: Jill

Pick an item from the menu: 10 . Jack1 . Jill

Pick an item from the menu: 3What name would you like to remove: Jack

Pick an item from the menu: 4What name would you like to change: JillWhat is the new name: Jill Peters

Pick an item from the menu: 10 . Jill Peters

Pick an item from the menu: 9Goodbye

Thatwasa long program.Let’s take a look at thesourcecode.Theline list = [] makesthevariablelist a listwith no items(or elements).The next importantline is while menu_item != 9: . This line startsa loop thatallows themenusystemfor this program.Thenext few linesdisplaya menuanddecidewhich partof theprogramtorun.

Thesection:

current = 0if len(list) > 0:

while current < len(list):print current,". ",list[current]current = current + 1

else:print "List is empty"

goesthroughthe list andprintseachname.len(list_name) tell how many itemsarein a list. If len returns0thenthelist is empty.

Thena few lines later thestatementlist.append(name) appears.It usestheappend functionto adda item totheendof thelist. Jumpdown anothertwo linesandnoticethis sectionof code:

item_number = list.index(del_name)del list[item_number]

Here the index function is used to find the index value that will be used later to remove the item.del list[item_number] is usedto removea elementof thelist.

8.2. More features of lists 37

Page 44: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

Thenext section

old_name = raw_input("What name would you like to change: ")if old_name in list:

item_number = list.index(old_name)new_name = raw_input("What is the new name: ")list[item_number] = new_name

else:print old_name," was not found"

usesindex to find the item_number andthenputsnew_name wheretheold_name was.

8.3 Examples

test.py

## This program runs a test of knowledge

true = 1false = 0

# First get the test questions# Later this will be modified to use file io.def get_questions():

# notice how the data is stored as a list of listsreturn [["What color is the daytime sky on a clear day?","blue"],\

["What is the answer to life, the universe and everything?","42"],\["What is a three letter word for mouse trap?","cat"]]

# This will test a single question# it takes a single question in# it returns true if the user typed the correct answer, otherwise falsedef check_question(question_and_answer):

#extract the question and the answer from the listquestion = question_and_answer[0]answer = question_and_answer[1]# give the question to the usergiven_answer = raw_input(question)# compare the user’s answer to the testers answerif answer == given_answer:

print "Correct"return true

else:print "Incorrect, correct was:",answerreturn false

38 Chapter 8. Lists

Page 45: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

# This will run through all the questionsdef run_test(questions):

if len(questions) == 0:print "No questions were given."# the return exits the functionreturn

index = 0right = 0while index < len(questions):

#Check the questionif check_question(questions[index]):

right = right + 1#go to the next questionindex = index + 1

#notice the order of the computation, first multiply, then divideprint "You got ",right*100/len(questions),"% right out of",len(questions)

#now lets run the questionsrun_test(get_questions())

SampleOutput:

What color is the daytime sky on a clear day?greenIncorrect, correct was: blueWhat is the answer to life, the universe and everything?42CorrectWhat is a three letter word for mouse trap?catCorrectYou got 66 % right out of 3

8.4 Exercises

Expandthe test.py programso it hasmenugiving the option of taking the test, viewing the list of questionsandanswers,andanoptionto Quit. Also, adda new questionto ask,”What noisedoesa truly advancedmachinemake?”with theanswerof ”ping”.

8.4. Exercises 39

Page 46: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

40

Page 47: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

CHAPTER

NINE

For Loops

And hereis thenew typingexercisefor this chapter:

onetoten = range(1,11)for count in onetoten:

print count

andtheever-presentoutput:

12345678910

Theoutputlooksawfully familiar but theprogramcodelooksdifferent.Thefirst line usesthe range function. Therange functionusestwo argumentslikethisrange(start,finish) . start is thefirst numberthatisproduced.finish is onelargerthanthelastnumber. Notethatthis programcouldhavebeendonein ashorterway:

for count in range(1,11):print count

Herearesomeexamplesto show whathappenswith therange command:

>>> range(1,10)[1, 2, 3, 4, 5, 6, 7, 8, 9]>>> range(-32, -20)[-32, -31, -30, -29, -28, -27, -26, -25, -24, -23, -22, -21]>>> range(5,21)[5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]>>> range(21,5)[]

Thenext line for count in onetoten: usesthefor controlstructure.A for controlstructurelookslike forvariable in list: . list is gonethroughstartingwith the first elementof the list andgoing to the last. Asfor goesthrougheachelementin a list it putseachinto variable . That allows variable to be usedin each

41

Page 48: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

successive time thefor loop is run through.Hereis anotherexample(youdon’t haveto typethis) to demonstrate:

demolist = [’life’,42, ’the universe’, 6,’and’,7,’everything’]for item in demolist:

print "The Current item is:",print item

Theoutputis:

The Current item is: lifeThe Current item is: 42The Current item is: the universeThe Current item is: 6The Current item is: andThe Current item is: 7The Current item is: everything

Noticehow thefor loop goesthroughandsetsitem to eachelementin thelist. (Noticehow if you don’t wantprintto go to thenext line adda commaat theendof thestatement(i.e. if you wantto print somethingelseon that line). )So,whatis for goodfor? (groan)Thefirst useis to go throughall theelementsof a list anddo somethingwith eachof them.Hereaquickway to addupall theelements:

l = [2,4,6,8]sum = 0for num in l:

sum = sum + numprint "The sum is: ",sum

with theoutputsimplybeing:

The sum is: 20

Or you couldwrite a programto find out if thereareany duplicatesin a list like this programdoes:

l = [4, 5, 7, 8, 9, 1,0,7,10]l.sort()prev = l[0]del l[0]for item in l:

if prev == item:print "Duplicate of ",prev," Found"

prev = item

andfor goodmeasure:

Duplicate of 7 Found

Okay, sohow doesit work? Hereis a specialdebuggingversionto helpyou understand(you don’t needto typethisin):

42 Chapter 9. For Loops

Page 49: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

l = [4, 5, 7, 8, 9, 1,0,7,10]print "l = [4, 5, 7, 8, 9, 1,0,7,10]","\tl:",ll.sort()print "l.sort()","\tl:",lprev = l[0]print "prev = l[0]","\tprev:",prevdel l[0]print "del l[0]","\tl:",lfor item in l:

if prev == item:print "Duplicate of ",prev," Found"

print "if prev == item:","\tprev:",prev,"\titem:",itemprev = itemprint "prev = item","\t\tprev:",prev,"\titem:",ite m

with theoutputbeing:

l = [4, 5, 7, 8, 9, 1,0,7,10] l: [4, 5, 7, 8, 9, 1, 0, 7, 10]l.sort() l: [0, 1, 4, 5, 7, 7, 8, 9, 10]prev = l[0] prev: 0del l[0] l: [1, 4, 5, 7, 7, 8, 9, 10]if prev == item: prev: 0 item: 1prev = item prev: 1 item: 1if prev == item: prev: 1 item: 4prev = item prev: 4 item: 4if prev == item: prev: 4 item: 5prev = item prev: 5 item: 5if prev == item: prev: 5 item: 7prev = item prev: 7 item: 7Duplicate of 7 Foundif prev == item: prev: 7 item: 7prev = item prev: 7 item: 7if prev == item: prev: 7 item: 8prev = item prev: 8 item: 8if prev == item: prev: 8 item: 9prev = item prev: 9 item: 9if prev == item: prev: 9 item: 10prev = item prev: 10 item: 10

The reasonI put so many print statementsin the codewasso that you canseewhat is happeningin eachline.(BTW, if you can’t figure out why a programis not working, try putting in lots of print statementsto you canseewhat is happening)First theprogramstartswith a boringold list. Next theprogramsortsthe list. This is sothatanyduplicatesgetput next to eachother. Theprogramtheninitializesa prev(ious)variable.Next thefirst elementof thelist is deletedsothatthefirst item is not incorrectlythoughtto bea duplicate.Next a for loop is goneinto. Eachitemof the list is checkedto seeif it is thesameastheprevious. If it is a duplicatewasfound. Thevalueof prev is thenchangedsothatthenext time thefor loop is run throughprev is thepreviousitemto thecurrent.Sureenough,the7 isfoundto bea duplicate.(Noticehow \t is usedto print a tab.)

Theotherway to usefor loopsis to do somethinga certainnumberof times. Hereis somecodeto print out thefirst11 numbersof theFibonacciseries:

43

Page 50: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

a = 1b = 1for c in range(1,10):

print a,n = a + ba = bb = n

with thesurprisingoutput:

1 1 2 3 5 8 13 21 34

Everythingthatcanbedonewith for loopscanalsobedonewith while loopsbut for loopsgiveaeasyway to gothroughall theelementsin a list or to do somethinga certainnumberof times.

44 Chapter 9. For Loops

Page 51: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

CHAPTER

TEN

Boolean Expressions

Hereis a little exampleof booleanexpressions(youdon’t have to typeit in):

a = 6b = 7c = 42print 1, a == 6print 2, a == 7print 3,a == 6 and b == 7print 4,a == 7 and b == 7print 5,not a == 7 and b == 7print 6,a == 7 or b == 7print 7,a == 7 or b == 6print 8,not (a == 7 and b == 6)print 9,not a == 7 and b == 6

With theoutputbeing:

1 12 03 14 05 16 17 08 19 0

What is going on? The programconsistsof a bunchof funny looking print statements.Eachprint statementprintsanumberandaexpression.Thenumberis to helpkeeptrackof whichstatementI amdealingwith. Noticehoweachexpressionendsup beingeither0 or 1. In Pythonfalseis writtenas0 andtrueis writtenas1. Thelines:

print 1, a == 6print 2, a == 7

print out a 1 and a 0 respectively just as expectedsincethe first is true and the secondis false. The third print,print 3,a == 6 and b == 7, is a little different. Theoperatorand meansif both thestatementbeforeandthestatementafteraretrue thenthewholeexpressionis trueotherwisethewholeexpressionis false. Thenext line,print 4,a == 7 and b == 7, shows how if partof anand expressionis false,thewholething is false.Thebehavior of and canbesummarizedasfollows:

45

Page 52: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

expression resulttrueandtrue truetrueandfalse falsefalseandtrue falsefalseandfalse false

Notice that if the first expressionis falsePythondoesnot checkthe secondexpressionsinceit knows the wholeexpressionis false.

Thenext line, print 5,not a == 7 and b == 7, usesthenot operator. not just givestheoppositeof theexpression(Theexpressioncouldberewrittenasprint 5,a != 7 and b == 7). Heresthetable:

expression resultnot true falsenot false true

The two following lines, print 6,a == 7 or b == 7 and print 7,a == 7 or b == 6, use the oroperator. The or operatorreturnstrue if the first expressionis true, or if the secondexpressionis true or both aretrue. If neitheraretrueit returnsfalse.Here’s thetable:

expression resulttrueor true truetrueor false truefalseor true truefalseor false false

Noticethatif thefirst expressionis truePythondoesn’t checkthesecondexpressionsinceit knows thewholeexpres-sionis true.Thisworkssinceor is trueif at leastonehalf of theexpressionis true.Thefirst partis truesothesecondpartcouldbeeitherfalseor true,but thewholeexpressionis still true.

The next two lines, print 8,not (a == 7 and b == 6) and print 9,not a == 7 and b == 6,show that parenthesescan be usedto group expressionsand force one part to be evaluatedfirst. Notice that theparentheseschangedtheexpressionfrom falseto true.Thisoccurredsincetheparenthesesforcedthenot to applytothewholeexpressioninsteadof just thea == 7 portion.

Hereis anexampleof usingabooleanexpression:

list = ["Life","The Universe","Everything","Jack","Jill"," Life", "Jill" ]

#make a copy of the listcopy = list[:]#sort the copycopy.sort()prev = copy[0]del copy[0]

count = 0

#go through the list searching for a matchwhile count < len(copy) and copy[count] != prev:

prev = copy[count]count = count + 1

#If a match was not found then count can’t be < len#since the while loop continues while count is < len#and no match is foundif count < len(copy):

print "First Match: ",prev

46 Chapter 10. Boolean Expressions

Page 53: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

And hereis theoutput:

First Match: Jill

This program works by continuing to check for match while count < len(copy and copy[count] .When eithercount is greaterthan the last index of copy or a matchhasbeenfound the and is no longer truesotheloopexits. The if simply checksto makesurethatthewhile exited becausea matchwasfound.

Theother‘trick’ of and is usedin this example. If you look at thetablefor and noticethat thethird entry is “f alseandwon’t check”. If count >= len(copy) (in otherwordscount < len(copy) is false)thencopy[count]is never lookedat. This is becausePythonknows that if thefirst is falsethenthey bothcan’t betrue. This is knownasa shortcircuit andis usefulif thesecondhalf of theand will causeanerrorif somethingis wrong. I usedthefirstexpression(count < len(copy) ) to checkandseeif count wasa valid index for copy . (If you don’t believemeremovethematches‘Jill’ and‘Life’, checkthatit still worksandthenreversetheorderof count < len(copy)and copy[count] != prev to copy[count] != prev and count < len(copy) .)

Booleanexpressionscanbeusedwhenyouneedto checktwo or moredifferentthingsat once.

10.1 Examples

password1.py

## This programs asks a user for a name and a password.# It then checks them to make sure the the user is allowed in.

name = raw_input("What is your name? ")password = raw_input("What is the password? ")if name == "Josh" and password == "Friday":

print "Welcome Josh"elif name == "Fred" and password == "Rock":

print "Welcome Fred"else:

print "I don’t know you."

Sampleruns

What is your name? JoshWhat is the password? FridayWelcome Josh

What is your name? BillWhat is the password? MoneyI don’t know you.

10.1. Examples 47

Page 54: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

48

Page 55: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

CHAPTER

ELEVEN

Dictionaries

This chapteris aboutdictionaries.Dictionarieshavekeys andvalues.Thekeysareusedto find thevalues.Hereis anexampleof adictionaryin use:

def print_menu():print ’1. Print Phone Numbers’print ’2. Add a Phone Number’print ’3. Remove a Phone Number’print ’4. Lookup a Phone Number’print ’5. Quit’print

numbers = {}menu_choice = 0print_menu()while menu_choice != 5:

menu_choice = input("Type in a number (1-5):")if menu_choice == 1:

print "Telephone Numbers:"for x in numbers.keys():

print "Name: ",x," \tNumber: ",numbers[x]print

elif menu_choice == 2:print "Add Name and Number"name = raw_input("Name:")phone = raw_input("Number:")numbers[name] = phone

elif menu_choice == 3:print "Remove Name and Number"name = raw_input("Name:")if numbers.has_key(name):

del numbers[name]else:

print name," was not found"elif menu_choice == 4:

print "Lookup Number"name = raw_input("Name:")if numbers.has_key(name):

print "The number is",numbers[name]else:

print name," was not found"elif menu_choice != 5:

print_menu()

And hereis my output:

49

Page 56: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

1. Print Phone Numbers2. Add a Phone Number3. Remove a Phone Number4. Lookup a Phone Number5. Quit

Type in a number (1-5):2Add Name and NumberName:JoeNumber:545-4464Type in a number (1-5):2Add Name and NumberName:JillNumber:979-4654Type in a number (1-5):2Add Name and NumberName:FredNumber:132-9874Type in a number (1-5):1Telephone Numbers:Name: Jill Number: 979-4654Name: Joe Number: 545-4464Name: Fred Number: 132-9874

Type in a number (1-5):4Lookup NumberName:JoeThe number is 545-4464Type in a number (1-5):3Remove Name and NumberName:FredType in a number (1-5):1Telephone Numbers:Name: Jill Number: 979-4654Name: Joe Number: 545-4464

Type in a number (1-5):5

This programis similar to the namelist earlierin the the chapteron lists. Hereshow the programworks. First thefunction print_menu is defined. print_menu just prints a menuthat is later usedtwice in the program. Nextcomesthefunny looking line numbers = {} . All that line doesis tell Pythonthatnumbers is a dictionary. Thenext few linesjust make themenuwork. Thelines:

for x in numbers.keys():print "Name: ",x," \tNumber: ",numbers[x]

go throughthe dictionaryandprint all the information. The function numbers.keys() returnsa list that is thenusedby the for loop. The list returnedby keys is not in any particularorderso if you want it in alphabeticorderit mustbesorted.Similar to lists thestatementnumbers[x] is usedto accessa specificmemberof thedictionary.Of coursein this casex is a string. Next the line numbers[name] = phone addsa nameandphonenumbertothedictionary. If name hadalreadybeenin thedictionaryphone would replacewhateverwastherebefore.Next thelines:

50 Chapter 11. Dictionaries

Page 57: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

if numbers.has_key(name):del numbers[name]

seeif a nameis in the dictionaryandremove it if it is. The function numbers.has_key(name) returnstrue ifname is in numbers but otherwisereturnsfalse.Theline del numbers[name] removesthekey name andthevalueassociatedwith thatkey. Thelines:

if numbers.has_key(name):print "The number is",numbers[name]

checkto seeif the dictionaryhasa certainkey andif it doesprints out the numberassociatedwith it. Lastly if themenuchoiceis invalid it reprintsthemenufor yourviewing pleasure.

A recap:Dictionarieshavekeys andvalues.Keyscanbestringsor numbers.Keys point to values.Valuescanbeanytype of variable(including lists or evendictionaries(thosedictionariesor lists of coursecancontaindictionariesorlists themselves(scaryright? :) )). Hereis anexampleof usinga list in a dictionary:

max_points = [25,25,50,25,100]assignments = [’hw ch 1’,’hw ch 2’,’quiz ’,’hw ch 3’,’test’]students = {’#Max’:max_points}

def print_menu():print "1. Add student"print "2. Remove student"print "3. Print grades"print "4. Record grade"print "5. Print Menu"print "6. Exit"

def print_all_grades():print ’\t’,for i in range(len(assignments)):

print assignments[i],’\t’,printkeys = students.keys()keys.sort()for x in keys:

print x,’\t’,grades = students[x]print_grades(grades)

def print_grades(grades):for i in range(len(grades)):

print grades[i],’\t\t’,print

51

Page 58: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

print_menu()menu_choice = 0while menu_choice != 6:

printmenu_choice = input("Menu Choice (1-6):")if menu_choice == 1:

name = raw_input("Student to add:")students[name] = [0]*len(max_points)

elif menu_choice == 2:name = raw_input("Student to remove:")if students.has_key(name):

del students[name]else:

print "Student: ",name," not found"elif menu_choice == 3:

print_all_grades()

elif menu_choice == 4:print "Record Grade"name = raw_input("Student:")if students.has_key(name):

grades = students[name]print "Type in the number of the grade to record"print "Type a 0 (zero) to exit"for i in range(len(assignments)):

print i+1,’ ’,assignments[i],’\t’,printprint_grades(grades)which = 1234while which != -1:

which = input("Change which Grade:")which = which-1if 0 <= which < len(grades):

grade = input("Grade:")grades[which] = grade

elif which != -1:print "Invalid Grade Number"

else:print "Student not found"

elif menu_choice != 6:print_menu()

andhereis a sampleoutput:

1. Add student2. Remove student3. Print grades4. Record grade5. Print Menu6. Exit

Menu Choice (1-6):3hw ch 1 hw ch 2 quiz hw ch 3 test

#Max 25 25 50 25 100

52 Chapter 11. Dictionaries

Page 59: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

Menu Choice (1-6):61. Add student2. Remove student3. Print grades4. Record grade5. Print Menu6. Exit

Menu Choice (1-6):1Student to add:Bill

Menu Choice (1-6):4Record GradeStudent:BillType in the number of the grade to recordType a 0 (zero) to exit1 hw ch 1 2 hw ch 2 3 quiz 4 hw ch 3 5 test0 0 0 0 0Change which Grade:1Grade:25Change which Grade:2Grade:24Change which Grade:3Grade:45Change which Grade:4Grade:23Change which Grade:5Grade:95Change which Grade:0

Menu Choice (1-6):3hw ch 1 hw ch 2 quiz hw ch 3 test

#Max 25 25 50 25 100Bill 25 24 45 23 95

Menu Choice (1-6):6

Hereshow the programworks. Basically the variablestudents is a dictionary with the keys being the nameof the studentsand the values being their grades. The first two lines just create two lists. The next linestudents = {’#Max’:max_points} createsa new dictionarywith the key #Max andthe valueis set to be[25,25,50,25,100] (sincethatswhat max_points waswhenthe assignmentis made)(I usethe key #Maxsince# is sortedaheadof any alphabeticcharacters).Next print_menu is defined.Next theprint_all_gradesfunctionis definedin thelines:

53

Page 60: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

def print_all_grades():print ’\t’,for i in range(len(assignments)):

print assignments[i],’\t’,printkeys = students.keys()keys.sort()for x in keys:

print x,’\t’,grades = students[x]print_grades(grades)

Notice how first the keys aregottenout of the students dictionarywith the keys function in the line keys =students.keys() . keys is a list soall thefunctionsfor lists canbeusedon it. Next thekeys aresortedin theline keys.sort() sinceit is a list. for is usedto go throughall the keys. The gradesarestoredasa list insidethedictionarysotheassignmentgrades = students[x] givesgrades thelist thatis storedat thekey x . Thefunctionprint_grades just printsa list andis defineda few lineslater.

The later lines of the program implement the various options of the menu. The linestudents[name] = [0]*len(max_points) adds a student to the key of their name. The notation[0]*len(max_points) just createsa arrayof 0’s thatis thesamelengthasthemax_points list.

The remove studententry just deletesa studentsimilar to the telephonebookexample. The recordgradeschoiceisa little morecomplex. Thegradesareretrieved in the line grades = students[name] getsa referenceto thegradesof thestudentname. A gradeis thenrecordedin theline grades[which] = grade . You maynoticethatgrades is never put backinto thestudentsdictionary(asin no students[name] = grades ). The reasonforthe missingstatementis that grades is actuallyanothernamefor students[name] andso changinggradeschangesstudent[name] .

Dictionariesprovidea easyway to link keys to values.Thiscanbeusedto easilykeeptrackof datathatis attachedtovariouskeys.

54 Chapter 11. Dictionaries

Page 61: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

CHAPTER

TWELV

Using Modules

Here’s this chapter’s typingexercise(nameit cal.py)1:

import calendar

year = input("Type in the year number:")calendar.prcal(year)

And hereis partof theoutputI got:

Type in the year number:20012001

January February MarchMo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su

1 2 3 4 5 6 7 1 2 3 4 1 2 3 48 9 10 11 12 13 14 5 6 7 8 9 10 11 5 6 7 8 9 10 11

15 16 17 18 19 20 21 12 13 14 15 16 17 18 12 13 14 15 16 17 1822 23 24 25 26 27 28 19 20 21 22 23 24 25 19 20 21 22 23 24 2529 30 31 26 27 28 26 27 28 29 30 31

(I skippedsomeof the output,but I think you get the idea.) Sowhat doesthe programdo? The first line importcalendar usesa new commandimport . The commandimport loadsa module(in this casethe calendarmodule). To seethe commandsavailable in the standardmoduleseither look in the library referencefor python(if you downloadedit) or go to http://www.python.org/doc/current/l ib/li b.htm l . The calendarmoduleis describedin 5.9. If you look at thedocumentationlists a functioncalledprcal thatprintsa calendarfor ayear. Theline calendar.prcal(year) usesthefunction. In summaryto usea moduleimport it andthenusemodule name.functionfor functionsin themodule.Anotherway to write theprogramis:

from calendar import prcal

year = input("Type in the year number:")prcal(year)

This versionimportsa specificfunctionfrom a module.Hereis anotherprogramthatusesthePythonLibrary (nameit somethinglikeclock.py) (pressCtrl andthe’c’ key at thesametime to kill theprogram):

1import actuallylooksfor a file namedcalendar.py andreadsit in. If thefile is namedcalendar.py andit seesa ’import calendar’it triesto readin itself whichworkspoorlyatbest.

55

Page 62: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

from time import time, ctime

prev_time = ""while(1):

the_time = ctime(time())if(prev_time != the_time):

print "The time is:",ctime(time())prev_time = the_time

With someoutputbeing:

The time is: Sun Aug 20 13:40:04 2000The time is: Sun Aug 20 13:40:05 2000The time is: Sun Aug 20 13:40:06 2000The time is: Sun Aug 20 13:40:07 2000Traceback (innermost last):

File "clock.py", line 5, in ?the_time = ctime(time())

KeyboardInterrupt

Theoutputis infinite of coursesoI canceledit (or theoutputat leastcontinuesuntil Ctrl+C is pressed).Theprogramjustdoesa infinite loopandeachtimechecksto seeif thetimehaschangedandprintsit if it has.Noticehow multiplenamesaftertheimport statementareusedin theline from time import time, ctime .

ThePythonLibrary containsmany usefulfunctions.Thesefunctionsgive your programsmoreabilitiesandmany ofthemcansimplify programmingin Python.

12.1 Exercises

Rewrite thehigh low.py programfrom section5.2to usethelasttwo digitsof timeat thatmomentto bethe’random’number.

56 Chapter 12. Using Modules

Page 63: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

CHAPTER

THIRTEEN

More on Lists

We have alreadyseenlists andhow they canbeused.Now thatyou have somemorebackgroundI will go into moredetailaboutlists. First we will look at morewaysto getat theelementsin a list andthenwe will talk aboutcopyingthem.

Herearesomeexamplesof usingindexing to accessa singleelementof anlist:

>>> list = [’zero’,’one’,’two’,’three’,’four’,’five’ ]>>> list[0]’zero’>>> list[4]’four’>>> list[5]’five’

All thoseexamplesshouldlook familiar to you. If you want thefirst item in the list just look at index 0. Theseconditem is index 1 andsoon throughthe list. However what if you want the last item in the list? Oneway couldbe tousethe len function like list[len(list)-1] . This way workssincethe len functionalwaysreturnsthe lastindex plusone.Thesecondfrom the lastwould thenbe list[len(list)-2] . Thereis aneasierway to do this.In Pythonthelastitemis alwaysindex -1. Thesecondto thelastis index -2 andsoon. Herearesomemoreexamples:

>>> list[len(list)-1]’five’>>> list[len(list)-2]’four’>>> list[-1]’five’>>> list[-2]’four’>>> list[-6]’zero’

Thusany item in thelist canbeindexedin two ways:from thefront andfrom theback.

Anotherusefulway to getinto partsof lists is usingslices.Hereis anotherexampleto giveyouanideawhatthey canbeusedfor:

57

Page 64: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

>>> list = [0,’Fred’,2,’S.P.A.M.’,’Stocking’,42,"Jac k","Ji ll"]>>> list[0]0>>> list[7]’Jill’>>> list[0:8][0, ’Fred’, 2, ’S.P.A.M.’, ’Stocking’, 42, ’Jack’, ’Jill’]>>> list[2:4][2, ’S.P.A.M.’]>>> list[4:7][’Stocking’, 42, ’Jack’]>>> list[1:5][’Fred’, 2, ’S.P.A.M.’, ’Stocking’]

Slices are used to return part of a list. The slice operator is in the formlist[first_index:following_index] . The slice goes from the first_index to the index beforethefollowing_index . Youcanusebothtypesof indexing:

>>> list[-4:-2][’Stocking’, 42]>>> list[-4]’Stocking’>>> list[-4:6][’Stocking’, 42]

Anothertrick with slicesis theunspecifiedindex. If thefirst index is notspecifiedthebeginningof thelist is assumed.If thefollowing index is not specifiedthewholerestof thelist is assumed.Herearesomeexamples:

>>> list[:2][0, ’Fred’]>>> list[-2:][’Jack’, ’Jill’]>>> list[:3][0, ’Fred’, 2]>>> list[:-5][0, ’Fred’, 2]

Hereis a programexample(copy andpastein thepoemdefinitionif youwant):

58 Chapter 13. More on Lists

Page 65: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

poem = ["<B>","Jack","and","Jill","</B>","went ","up" ,"the" ,"hill ","to" ,"<B>" ,\"fetch","a","pail","of","</B>","water.", "Jack" ,"fell ","<B> ","dow n","an d",\"broke","</B>","his","crown","and","<B>" ,"Jill ","cam e","</ B>","t umblin g",\"after"]

def get_bolds(list):true = 1false = 0## is_bold tells whether or not the we are currently looking at## a bold section of text.is_bold = false## start_block is the index of the start of either an unbolded## segment of text or a bolded segment.start_block = 0for index in range(len(list)):

##Handle a starting of bold textif list[index] == "<B>":

if is_bold:print "Error: Extra Bold"

##print "Not Bold:",list[start_block:index]is_bold = truestart_block = index+1

##Handle end of bold textif list[index] == "</B>":

if not is_bold:print "Error: Extra Close Bold"

print "Bold [",start_block,":",index,"] ",\list[start_block:index]is_bold = falsestart_block = index+1

get_bolds(poem)

with theoutputbeing:

Bold [ 1 : 4 ] [’Jack’, ’and’, ’Jill’]Bold [ 11 : 15 ] [’fetch’, ’a’, ’pail’, ’of’]Bold [ 20 : 23 ] [’down’, ’and’, ’broke’]Bold [ 28 : 30 ] [’Jill’, ’came’]

The get_bold function takesin a list that is broken into wordsandtoken’s. The tokensthat it looks for are<B>whichstartsthebold text and<\B> whichendsbold text. Thefunctionget_bold goesthroughandsearchesfor thestartandendtokens.

Thenext featureof lists is copying them.If you try somethingsimplelike:

>>> a = [1,2,3]>>> b = a>>> print b[1, 2, 3]>>> b[1] = 10>>> print b[1, 10, 3]>>> print a[1, 10, 3]

59

Page 66: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

This probablylookssurprisingsincea modificationto b resultedin a beingchangedaswell. Whathappenedis thatthestatementb = a makesb a reference to a. This meansthatb canbe thoughtof asanothernamefor a. Henceany modificationto b changesa aswell. Howeversomeassignmentsdon’t createtwo namesfor onelist:

>>> a = [1,2,3]>>> b = a*2>>> print a[1, 2, 3]>>> print b[1, 2, 3, 1, 2, 3]>>> a[1] = 10>>> print a[1, 10, 3]>>> print b[1, 2, 3, 1, 2, 3]

In this caseb is not a referenceto a sincetheexpressiona*2 createsa new list. Thenthestatementb = a*2 givesb a referenceto a*2 ratherthana referenceto a. All assignmentoperationscreatea reference.Whenyou passa listasa argumentto a functionyou createa referenceaswell. Most of the time you don’t have to worry aboutcreatingreferencesratherthancopies. However whenyou needto make modificationsto onelist without changinganothernameof thelist youhave to makesurethatyou haveactuallycreateda copy.

Thereareseveralwaysto makea copy of a list. Thesimplestthatworksmostof thetime is thesliceoperatorsinceitalwaysmakesanew list evenif it is a sliceof awholelist:

>>> a = [1,2,3]>>> b = a[:]>>> b[1] = 10>>> print a[1, 2, 3]>>> print b[1, 10, 3]

Takingtheslice [:] createsa new copy of thelist. However it only copiestheouterlist. Any sublistinsideis still areferencesto thesublistin theoriginal list. Therefore,whenthe list containslists the inner lists have to becopiedaswell. You coulddo thatmanuallybut Pythonalreadycontainsa moduleto do it. You usethedeepcopy functionofthecopy module:

>>> import copy>>> a = [[1,2,3],[4,5,6]]>>> b = a[:]>>> c = copy.deepcopy(a)>>> b[0][1] = 10>>> c[1][1] = 12>>> print a[[1, 10, 3], [4, 5, 6]]>>> print b[[1, 10, 3], [4, 5, 6]]>>> print c[[1, 2, 3], [4, 12, 6]]

Firstof all noticethata is anarrayof arrays.Thennoticethatwhenb[0][1] = 10 is runbotha andb arechanged,but c is not. This happensbecausetheinnerarraysarestill referenceswhenthesliceoperatoris used.Howeverwithdeepcopy c wasfully copied.

60 Chapter 13. More on Lists

Page 67: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

So,shouldI worry aboutreferencesevery time I usea functionor =? Thegoodnews is thatyou only have to worryaboutreferenceswhenusingdictionariesandlists. Numbersandstringscreatereferenceswhenassignedbut everyoperationon numbersandstringsthatmodifiesthemcreatesa new copy soyou cannevermodify themunexpectedly.You dohave to think aboutreferenceswhenyou aremodifyinga list or a dictionary.

By now you areprobablywonderingwhy arereferencesusedat all? Thebasicreasonis speed.It is muchfastertomake a referenceto a thousandelementlist thanto copy all the elements.The otherreasonis that it allows you tohave a functionto modify theinputedlist or dictionary. Justrememberaboutreferencesif you everhave someweirdproblemwith databeingchangedwhenit shouldn’t be.

61

Page 68: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

62

Page 69: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

CHAPTER

FOURTEEN

Revenge of the Strings

And now presentinga cool trick thatcanbedonewith strings:

def shout(string):for character in string:

print "Gimme a "+characterprint "’"+character+"’"

shout("Lose")

def middle(string):print "The middle character is:",string[len(string)/2]

middle("abcdefg")middle("The Python Programming Language")middle("Atlanta")

And theoutputis:

Gimme a L’L’Gimme a o’o’Gimme a s’s’Gimme a e’e’The middle character is: dThe middle character is: rThe middle character is: a

Whattheseprogramsdemonstrateis thatstringsaresimilar to lists in severalways.Theshout procedureshowsthatfor loopscanbeusedwith stringsjust asthey canbeusedwith lists. Themiddleprocedureshows that thatstringscanalsousethe len functionandarrayindexesandslices.Most list featureswork on stringsaswell.

Thenext featuredemonstratessomestringspecificfeatures:

63

Page 70: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

def to_upper(string):## Converts a string to upper caseupper_case = ""for character in string:

if ’a’ <= character <= ’z’:location = ord(character) - ord(’a’)new_ascii = location + ord(’A’)character = chr(new_ascii)

upper_case = upper_case + characterreturn upper_case

print to_upper("This is Text")

with theoutputbeing:

THIS IS TEXT

This works becausethe computerrepresentsthe charactersof a string as numbersfrom 0 to 255. Pythonhasafunction called ord (short for ordinal) that returnsa characteras a number. Thereis also a correspondingfunc-tion called chr that convertsa numberinto a character. With this in mind the programshouldstart to be clear.The first detail is the line: if ’a’ <= character <= ’z’: which checksto seeif a letter is lower case. Ifit is thanthe next lines areused. First it is convertedinto a locationso that a=0,b=1,c=2andso on with the line:location = ord(character) - ord(’a’) . Next the new value is found with new_ascii = loca-tion + ord(’A’) . Thisvalueis convertedbackto a characterthatis now uppercase.

Now for someinteractive typingexercise:

64 Chapter 14. Revenge of the Strings

Page 71: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

>>> #Integer to String...>>> 22>>> repr(2)’2’>>> -123-123>>> repr(-123)’-123’>>> #String to Integer...>>> "23"’23’>>> int("23")23>>> "23"*2’2323’>>> int("23")*246>>> #Float to String...>>> 1.231.23>>> repr(1.23)’1.23’>>> #Float to Integer...>>> 1.231.23>>> int(1.23)1>>> int(-1.23)-1>>> #String to Float...>>> float("1.23")1.23>>> "1.23"’1.23’>>> float("123")123.0

If you haven’t guessedalreadythefunction repr canconverta integerto a stringandthefunction int canconverta string to an integer. The function float canconvert a string to a float. The repr function returnsa printablerepresentationof something.Herearesomeexamplesof this:

>>> repr(1)’1’>>> repr(234.14)’234.14’>>> repr([4,42,10])’[4, 42, 10]’

The int function tries to convert a string (or a float) into a integer. Thereis alsoa similar function called floatthatwill converta integeror a string into a float. AnotherfunctionthatPythonhasis theeval function. Theeval

65

Page 72: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

functiontakesa stringandreturnsdataof thetypethatpythonthinksit found.For example:

>>> v=eval(’123’)>>> print v,type(v)123 <type ’int’>>>> v=eval(’645.123’)>>> print v,type(v)645.123 <type ’float’>>>> v=eval(’[1,2,3]’)>>> print v,type(v)[1, 2, 3] <type ’list’>

If youusetheeval functionyou shouldcheckthatit returnsthetypethatyouexpect.

Oneusefulstringfunctionis thesplit function.Here’s theexample:

>>> import string>>> string.split("This is a bunch of words")[’This’, ’is’, ’a’, ’bunch’, ’of’, ’words’]>>> string.split("First batch, second batch, third, fourth",",")[’First batch’, ’ second batch’, ’ third’, ’ fourth’]

Noticehow split convertsa string into a list of strings.Thestring is split by spacesby default or by theoptionalsecondargument(in this casea comma).

66 Chapter 14. Revenge of the Strings

Page 73: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

14.1 Examples

#This program requires a excellent understanding of decimal numbersdef to_string(in_int):

"Converts an integer to a string"out_str = ""prefix = ""if in_int < 0:

prefix = "-"in_int = -in_int

while in_int / 10 != 0:out_str = chr(ord(’0’)+in_int % 10) + out_strin_int = in_int / 10

out_str = chr(ord(’0’)+in_int % 10) + out_strreturn prefix + out_str

def to_int(in_str):"Converts a string to an integer"out_num = 0if in_str[0] == "-":

multiplier = -1in_str = in_str[1:]

else:multiplier = 1

for x in range(0,len(in_str)):out_num = out_num * 10 + ord(in_str[x]) - ord(’0’)

return out_num * multiplier

print to_string(2)print to_string(23445)print to_string(-23445)print to_int("14234")print to_int("12345")print to_int("-3512")

Theoutputis:

223445-234451423412345-3512

14.1. Examples 67

Page 74: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

68

Page 75: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

CHAPTER

FIFTEEN

File IO

Hereis a simpleexampleof file IO:

#Write a fileout_file = open("test.txt","w")out_file.write("This Text is going to out file\nLook at it and see\n")out_file.close()

#Read a filein_file = open("test.txt","r")text = in_file.read()in_file.close()

print text,

Theoutputandthecontentsof thefile test.txtare:

This Text is going to out fileLook at it and see

Notice that it wrote a file calledtest.txt in the directory that you ran the programfrom. The \n in the string tellsPythonto put a newline whereit is.

A overview of file IO is:

1. Geta file objectwith theopen function.

2. Reador write to thefile object(dependingonhow it wasopened)

3. Closeit

The first step is to get a file object. The way to do this is to use the open function. The format isfile_object = open(filename,mode) where file_object is the variable to put the file object,filename is a string with the filename,andmode is either "r" to reada file or "w" to write a file. Next thefile objectsfunctionscanbe called. The two mostcommonfunctionsareread andwrite . The write functionaddsa string to theendof thefile. The read functionreadsthenext thing in thefile andreturnsit asa string. If noargumentis givenit will returnthewholefile (asdonein theexample).

Now hereis anew versionof thephonenumbersprogramthatwe madeearlier:

69

Page 76: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

import string

def print_numbers(numbers):print "Telephone Numbers:"for x in numbers.keys():

print "Name: ",x," \tNumber: ",numbers[x]print

def add_number(numbers,name,number):numbers[name] = number

def lookup_number(numbers,name):if numbers.has_key(name):

return "The number is "+numbers[name]else:

return name+" was not found"

def remove_number(numbers,name):if numbers.has_key(name):

del numbers[name]else:

print name," was not found"

def load_numbers(numbers,filename):in_file = open(filename,"r")while 1:

in_line = in_file.readline()if in_line == "":

breakin_line = in_line[:-1][name,number] = string.split(in_line,",")numbers[name] = number

in_file.close()

def save_numbers(numbers,filename):out_file = open(filename,"w")for x in numbers.keys():

out_file.write(x+","+numbers[x]+"\n")out_file.close()

def print_menu():print ’1. Print Phone Numbers’print ’2. Add a Phone Number’print ’3. Remove a Phone Number’print ’4. Lookup a Phone Number’print ’5. Load numbers’print ’6. Save numbers’print ’7. Quit’print

70 Chapter 15. File IO

Page 77: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

phone_list = {}menu_choice = 0print_menu()while menu_choice != 7:

menu_choice = input("Type in a number (1-7):")if menu_choice == 1:

print_numbers(phone_list)elif menu_choice == 2:

print "Add Name and Number"name = raw_input("Name:")phone = raw_input("Number:")add_number(phone_list,name,phone)

elif menu_choice == 3:print "Remove Name and Number"name = raw_input("Name:")remove_number(phone_list,name)

elif menu_choice == 4:print "Lookup Number"

name = raw_input("Name:")print lookup_number(phone_list,name)

elif menu_choice == 5:filename = raw_input("Filename to load:")load_numbers(phone_list,filename)

elif menu_choice == 6:filename = raw_input("Filename to save:")save_numbers(phone_list,filename)

elif menu_choice == 7:pass

else:print_menu()

print "Goodbye"

Noticethatit now includessaving andloadingfiles. Hereis someoutputof my runningit twice:

71

Page 78: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

> python tele2.py1. Print Phone Numbers2. Add a Phone Number3. Remove a Phone Number4. Lookup a Phone Number5. Load numbers6. Save numbers7. Quit

Type in a number (1-7):2Add Name and NumberName:JillNumber:1234Type in a number (1-7):2Add Name and NumberName:FredNumber:4321Type in a number (1-7):1Telephone Numbers:Name: Jill Number: 1234Name: Fred Number: 4321

Type in a number (1-7):6Filename to save:numbers.txtType in a number (1-7):7Goodbye

> python tele2.py1. Print Phone Numbers2. Add a Phone Number3. Remove a Phone Number4. Lookup a Phone Number5. Load numbers6. Save numbers7. Quit

Type in a number (1-7):5Filename to load:numbers.txtType in a number (1-7):1Telephone Numbers:Name: Jill Number: 1234Name: Fred Number: 4321

Type in a number (1-7):7Goodbye

Thenew portionsof thisprogramare:

72 Chapter 15. File IO

Page 79: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

def load_numbers(numbers,filename):in_file = open(filename,"r")while 1:

in_line = in_file.readline()if len(in_line) == 0:

breakin_line = in_line[:-1][name,number] = string.split(in_line,",")numbers[name] = number

in_file.close()

def save_numbers(numbers,filename):out_file = open(filename,"w")for x in numbers.keys():

out_file.write(x+","+numbers[x]+"\n")out_file.close()

First we will look at the save portion of the program. First it createsa file object with the commandopen(filename,"w") . Next it goesthroughandcreatesa line for eachof the phonenumberswith the com-mandout_file.write(x+","+numbers[x]+"\n ") . Thiswritesouta line thatcontainsthename,acomma,thenumberandfollows it by anewline.

The loading portion is a little more complicated. It starts by getting a file object. Then it uses awhile 1: loop to keep looping until a break statementis encountered. Next it gets a line with the linein_line = in_file.readline() . Thegetline functionwill returna emptystring(len(string)== 0) whentheendof thefile is reached.Theif statementchecksfor thisandbreak soutof thewhile loopwhenthathappens.Of courseif thereadline functiondid notreturnthenewline at theendof theline therewouldbenowayto tell if anemptystringwasanemptyline or theendof thefile sothenewline is left in whatgetline returns.Hencewehavetogetrid of thenewline. Theline in_line = in_line[:-1] doesthis for usby droppingthelastcharacter. Nextthe line [name,number] = string.split(in_line,",") splits the line at thecommainto a nameandanumber. This is thenaddedto thenumbers dictionary.

15.1 Exercises

Now modify thegradesprogramfrom section11 sothatis usesfile IO to keepa recordof thestudents.

15.1. Exercises 73

Page 80: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

74

Page 81: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

CHAPTER

SIXTEEN

Dealing with the imperfect (or how tohandle errors)

Soyounow havetheperfectprogram,it runsflawlessly, exceptfor onedetail,it will crashon invalid userinput. Haveno fear, for Pythonhasa specialcontrol structurefor you. It’s called try andit tries to do something.Hereis anexampleof aprogramwith aproblem:

print "Type Control C or -1 to exit"number = 1while number != -1:

number = int(raw_input("Enter a number: "))print "You entered: ",number

Noticehow whenyou enter@#&it outputssomethinglike:

Traceback (innermost last):File "try_less.py", line 4, in ?

number = int(raw_input("Enter a number: "))ValueError: invalid literal for int(): @#&

As youcanseethe int functionis unhappy with thenumber@#&(aswell it shouldbe).Thelastline showswhattheproblemis; Pythonfounda ValueError . How canour programdealwith this? Whatwe do is first: put theplacewheretheerrorsoccursin a try block,andsecond:tell Pythonhow wewantValueError shandled.Thefollowingprogramdoesthis:

print "Type Control C or -1 to exit"number = 1while number != -1:

try:number = int(raw_input("Enter a number: "))print "You entered: ",number

except ValueError:print "That was not a number."

Now whenwe run thenew programandgive it @#&it tells us “That wasnot a number.” andcontinueswith what itwasdoingbefore.

Whenyourprogramkeepshaving someerrorthatyou know how to handle,put codein a try block,andput thewayto handletheerrorin theexcept block.

75

Page 82: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

16.1 Exercises

Updateat leastthephonenumbersprogramsoit doesn’t crashif a userdoesn’t enterany dataat themenu.

76 Chapter 16. Dealing with the imperfect (or how to handle errors)

Page 83: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

CHAPTER

SEVENTEEN

The End

I am currently working on addingmore sectionsto this document. For the momentI recommendlooking at ThePythonTutorial by GuidovanRossum.You shouldbeableto understanda fair amountof it.

This tutorial is very much a work in progress. I want any commentsyou have on what featuresyou would likedescribedin it. Thankyouemailshavebeenknown to causemeto getmassiveamountsof work done,improvements,andlisteningcloselyto comments:).

Happy programming,mayit changeyour life andtheworld.

TODO=[ ’errors’,’how to make modules’,’more on loops’,’more on strings’, ’file io’,’how to use onlinehelp’,’ try’,’pickle’,’anythinganyonesuggeststhatI think is a goodidea’]

77

Page 84: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

78

Page 85: Non-Programmers Tutorial For Pythonopim.wharton.upenn.edu/~sok/idtresources/python/easytut.pdf · Abstract Non-ProgrammersTutorial For Python is a tutorial designed to be a introduction

CHAPTER

EIGHTEEN

FAQ

Can’t useprogramswith input. If youareusingIDLE thentry usingcommandline. Thisproblemseemsto befixedin IDLE 0.6andnewer. If youareusinganolderversionof IDLE try upgradingto Python2.0or newer.

Is therea printable version? Yes,seethenext question.

Is therea PDF or zippedversion? Yes,go to http://www.honors.montana.edu/˜jjc/easytut/ for several differentver-sions.

What is the tutorial written with? LATEX, seethe‘easytut.tex’ file.

I can’t type in programsof more than oneline. If theprogramsthatyou typein runassoonasyouaretypingthemin, you needto edit a file insteadof typing themin interactive mode.(Hint: interactive modeis themodewiththe>>> promptin front of it.)

My questionis not answeredhere. Emailmeandask.Helpful thingsto includearewhatyouweretrying to do,whathappened,whatyou expectedto happen,errormessages,versionof Python,OperatingSystem,andwhetherornotyourcatwassteppingonthekeyboard.(Thecatin my househasafondnessfor spacebarsandcontrolkeys.)

What and whenwasthe last thing changed? 2000-Dec-16,addederrorhandlingchapter.2000-Dec-22,Removedold install procedure.2001-Jan-16,Fixedbug in program,Addedexampleanddatato lists section.2001-Apr-5,Spelling,grammar, addedanotherhow to breakprograms,url fix for PDFversion.2001-May-13,Addedchapteron debugging.2001-Nov-11,Addedexercises,fixedgrammar, spelling,andhopefullyimprovedexplanationsof somethings.2001-Nov-19,Addedpassword exercise,revisedreferencessection.

79