Table Of ContentNon-Programmers Tutorial For Python
Josh Cogliati
August4, 2005
Copyright(c)1999-2002JoshCogliati.
Permissionisgrantedtoanyonetomakeordistributeverbatimcopiesofthisdocumentasreceived,inanymedium,
provided that the copyright notice and permission notice are preserved, and that the distributor grants the recipient
permissionforfurtherredistributionaspermittedbythisnotice.
Permissionisgrantedtodistributemodifiedversionsofthisdocument,orofportionsofit,undertheaboveconditions,
providedalsothattheycarryprominentnoticesstatingwholastalteredthem.
All example python source code in this tutorial is granted to the public domain. Therefore you may modify it and
relicenseitunderanylicenseyouplease.
Abstract
Non-ProgrammersTutorialForPythonisatutorialdesignedtobeaintroductiontothePythonprogramminglanguage.
Thisguideisforsomeonewithnoprogrammingexperience.
IfyouhaveprogrammedinotherlanguagesIrecommendusingThePythonTutorialwrittenbyGuidovanRossum.
ThisdocumentisavailableasLATEX,HTML,PDF,andPostscript. Gotohttp://www.honors.montana.edu/˜jjc/easytut/
toseealltheseforms.
If you have any questions or comments please contact me at jjc@iname.com I welcome questions and comments
aboutthistutorial. IwilltrytoansweranyquestionsyouhaveasbestasIcan.
Thanks go to James A. Brown for writing most of the Windows install info. Thanks also to Elizabeth Cogliati for
complainingenough:)abouttheoriginaltutorial,(thatisalmostunusableforanon-programmer)forproofreadingand
formanyideasandcommentsonit. ThankstoJoeOppegaardforwritingalltheexercises.ThankstoeveryoneIhave
missed.
DedicatedtoElizabethCogliati
CONTENTS
1 Intro 1
1.1 Firstthingsfirst . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 InstallingPython . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.3 InteractiveMode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.4 CreatingandRunningPrograms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.5 UsingPythonfromthecommandline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
2 Hello,World 3
2.1 Whatyoushouldknow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.2 Printing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.3 Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.4 Talkingtohumans(andotherintelligentbeings) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.5 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3 WhoGoesThere? 9
3.1 InputandVariables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3.2 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
3.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
4 Countto10 13
4.1 Whileloops. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
4.2 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
5 Decisions 17
5.1 Ifstatement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
5.2 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
5.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
6 Debugging 23
6.1 Whatisdebugging? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
6.2 Whatshouldtheprogramdo? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
6.3 Whatdoestheprogramdo? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
6.4 HowdoIfixtheprogram? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
7 DefiningFunctions 29
7.1 CreatingFunctions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
7.2 Variablesinfunctions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
7.3 Functionwalkthrough . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
7.4 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
i
7.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
8 Lists 37
8.1 Variableswithmorethanonevalue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
8.2 Morefeaturesoflists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
8.3 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
8.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
9 ForLoops 45
10 BooleanExpressions 49
10.1 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
10.2 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
11 Dictionaries 53
12 UsingModules 59
12.1 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
13 MoreonLists 61
14 RevengeoftheStrings 67
14.1 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
15 FileIO 73
15.1 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
16 Dealingwiththeimperfect(orhowtohandleerrors) 79
16.1 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
17 TheEnd 81
18 FAQ 83
Index 85
ii
CHAPTER
ONE
Intro
1.1 First things first
So, you’ve never programmed before. As we go through this tutorial I will attempt to teach you how to program.
Therereallyisonlyonewaytolearntoprogram. Youmustreadcodeandwritecode. I’mgoingtoshowyoulotsof
code. YoushouldtypeincodethatIshowyoutoseewhathappens. Playaroundwithitandmakechanges.Theworst
thatcanhappenisthatitwon’twork. WhenItypeincodeitwillbeformattedlikethis:
##Python is easy to learn
print "Hello, World!"
That’ssoitiseasytodistinguishfromtheothertext. TomakeitconfusingIwillalsoprintwhatthecomputeroutputs
inthatsamefont.
Now, on to more important things. In order to program in Python you need the Python software. If you don’t
alreadyhavethePythonsoftwaregotohttp://www.python.org/download/andgettheproperversionforyourplatform.
Downloadit,readtheinstructionsandgetitinstalled.
1.2 Installing Python
Firstyouneedtodownloadtheappropriatefileforyourcomputerfromhttp://www.python.org/download. Gotothe2.0
link(ornewer)andthengetthewindowsinstallerifyouuseWindowsortherpmorsourceifyouuseUnix.
TheWindowsinstallerwilldownloadtofile.Thefilecanthenberunbydoubleclickingontheiconthatisdownloaded.
Theinstallationwillthenproceed.
IfyougettheUnixsourcemakesureyoucompileinthetkextensionifyouwanttouseIDLE.
1.3 Interactive Mode
GointoIDLE(alsocalledthePythonGUI).Youshouldseeawindowthathassometextlikethis:
1
Python 2.0 (#4, Dec 12 2000, 19:19:57)
[GCC 2.95.2 20000220 (Debian GNU/Linux)] on linux2
Type "copyright", "credits" or "license" for more information.
IDLE 0.6 -- press F1 for help
>>>
The>>>isPythonwayoftellingyouthatyouareininteractivemode. Ininteractivemodewhatyoutypeisimmedi-
atelyrun. Trytyping1+1in.Pythonwillrespondwith2. InteractivemodeallowsyoutotestoutandseewhatPython
willdo.IfyoueverfeelyouneedtoplaywithnewPythonstatementsgointointeractivemodeandtrythemout.
1.4 Creating and Running Programs
GointoIDLEifyouarenotalready.GotoFilethenNew Window.Inthiswindowtypethefollowing:
print "Hello, World!"
First save the program. Go to File then Save. Save it as ‘hello.py’. (If you want you can save it to some other
directorythanthedefault.)Nowthatitissaveditcanberun.
Nextrun the program bygoing toRun thenRun Module(or if you havea older versionofIDLEuse Edit then
Run script).ThiswilloutputHello, World!onthe*Python Shell*window.
Confusedstill? TrythistutorialforIDLEathttp://hkn.eecs.berkeley.edu/dyoo/python/idle intro/index.html
1.5 Using Python from the command line
If you don’twant to use Python from the command line, you don’thave too, just use IDLE. To get into interactive
mode just type python with out any arguments. To run a program create it with a text editor (Emacs has a good
pythonmode)andthenrunitwithpython program name.
2 Chapter1. Intro
CHAPTER
TWO
Hello, World
2.1 What you should know
YoushouldknowhowtoeditprogramsinatexteditororIDLE,savethemtodisk(floppyorhard)andrunthemonce
theyhavebeensaved.
2.2 Printing
ProgrammingtutorialssincethebeginningoftimehavestartedwithalittleprogramcalledHello,World! Sohereitis:
print "Hello, World!"
Ifyouareusingthecommandlinetorunprogramsthentypeitinwithatexteditor,saveitas‘hello.py’andrunitwith
“pythonhello.py”
OtherwisegointoIDLE,createanewwindow,andcreatetheprogramasinsection1.4.
Whenthisprogramisrunhere’swhatitprints:
Hello, World!
NowI’mnotgoingtotellyouthiseverytime,butwhenIshowyouaprogramIrecommendthatyoutypeitinandrun
it. IlearnbetterwhenItypeitinandyouprobablydotoo.
Nowhereisamorecomplicatedprogram:
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."
Whenyourunthisprogramitprintsout:
Jack and Jill went up a hill
to fetch a pail of water;
Jack fell down, and broke his crown,
and Jill came tumbling after.
3
Whenthecomputerrunsthisprogramitfirstseestheline:
print "Jack and Jill went up a hill"
sothecomputerprints:
Jack and Jill went up a hill
Thenthecomputergoesdowntothenextlineandsees:
print "to fetch a pail of water;"
Sothecomputerprintstothescreen:
to fetch a pail of water;
Thecomputerkeepslookingateachline,followsthecommandandthengoesontothenextline. Thecomputerkeeps
runningcommandsuntilitreachestheendoftheprogram.
2.3 Expressions
Hereisanotherprogram:
print "2 + 2 is", 2+2
print "3 * 4 is", 3 * 4
print 100 - 1, " = 100 - 1"
print "(33 + 2) / 5 + 11.5 = ",(33 + 2) / 5 + 11.5
Andhereistheoutputwhentheprogramisrun:
2 + 2 is 4
3 * 4 is 12
99 = 100 - 1
(33 + 2) / 5 + 11.5 = 18.5
AsyoucanseePythoncanturnyourthousanddollarcomputerintoa5dollarcalculator.
Pythonhassixbasicoperationsfornumbers:
Operation Symbol Example
Exponentiation ** 5 ** 2 == 25
Multiplication * 2 * 3 == 6
Division / 14 / 3 == 4
Remainder % 14 % 3 == 2
Addition + 1 + 2 == 3
Subtraction - 4 - 3 == 1
Noticethatdivisionfollowstherule,iftherearenodecimalstostartwith,therewillbenodecimalstoendwith.(Note:
ThiswillbechanginginPython2.3)Thefollowingprogramshowsthis:
4 Chapter2. Hello,World