Non-Programmer's Tutorial for Python 2.6/LaTeX
Appearance
\documentclass{manual}
\title{Non-Programmers Tutorial For Python}
\author{Josh Cogliati}
\newcommand{\type}[1]{``{\textsf{#1}}''}
\newcommand{\question}{{\bf Question: }}
\newcommand{\answer}{{\bf Answer: }}
%\input{boilerplate}
\makeindex % tell \index to actually write the .idx file
%\makemodindex % If this contains a lot of module sections.
\begin{document}
\maketitle
\newpage
{\bf Copyright(c) 1999-2002 Josh Cogliati. }
Permission is granted to anyone to make or distribute verbatim copies of this document as received, in any medium, provided that the copyright notice and permission notice are preserved, and that the distributor grants the recipient permission for further redistribution as permitted by this notice.
Permission is granted to distribute modified versions of this document, or of portions of it, under the above conditions, provided also that they carry prominent notices stating who last altered them.
All example python source code in this tutorial is granted to the public domain. Therefore you may modify it and relicense it under any license you please.
%%If you need to use this with normal LaTeX uncomment the next line and also
%%the end verbatim
%%\begin{verbatim}
% This makes the contents more accessible from the front page of the HTML.
\ifhtml
\chapter*{Front Matter\label{front}}
\fi
%\input{copyright}
\begin{abstract}
\noindent
Non-Programmers Tutorial For Python is a tutorial designed to be a introduction to the Python programming language. This guide is for someone with no programming experience.
If you have programmed in other languages I recommend using The Python Tutorial written by Guido van Rossum.
This document is available as \LaTeX, HTML, PDF, and Postscript. Go to http://www.honors.montana.edu/\~{}jjc/easytut/ to see all these forms.
If you have any questions or comments please contact me at jjc@iname.com \ I welcome questions and comments about this tutorial. I will try to answer any questions you have as best as I can.
Thanks go to James A. Brown for writing most of the Windows install
info. Thanks also to Elizabeth Cogliati for complaining enough :)
about the original tutorial,(that is almost unusable for a
non-programmer) for proofreading and for many ideas and comments on
it. Thanks to Joe Oppegaard for writing all the exercises. Thanks to
everyone I have missed.
\ifhtml
Here are a few links that you may find useful:
\begin{rawhtml}
<ul><li><a href="http://www.python.org">Python Home Page</a>
<li><a href="http://www.python.org/doc/">Python Documentation</a>}
<li><a href="http://www.python.org/doc/current/tut/tut.html">Python Tutorial for Programmers</a>
<li><a href="http://www.honors.montana.edu/~jjc/easytut/">LaTeX, PDF, and Postscript, and Zip versions</a>
</ul>
\end{rawhtml}
\fi
\newpage
\begin{center}
Dedicated to Elizabeth Cogliati
\end{center}
\end{abstract}
%%\end{verbatim}
\tableofcontents
\chapter{Intro}
\section{First things first}
So, you've never programmed before. As we go through this tutorial I
will attempt to teach you how to program. There really is only one
way to learn to program. {\bf You} must read code and write code.
I'm going to show you lots of code. You should type in code that I
show you to see what happens. Play around with it and make changes.
The worst that can happen is that it won't work. When I type in code
it will be formatted like this:
\begin{verbatim}
##Python is easy to learn
print "Hello, World!"
\end{verbatim}
That's so it is easy to distinguish from the other text. To make it confusing I will also print what the computer outputs in that same font.
Now, on to more important things. In order to program in Python you need the Python software. If you don't already have the Python software go to http://www.python.org/download/ and get the proper version for your platform. Download it, read the instructions and get it installed.
\section{Installing Python}
First you need to download the appropriate file for your computer from \url{http://www.python.org/download}. Go to the 2.0 link (or newer) and then get the windows installer if you use Windows or the rpm or source if you use Unix.
The Windows installer will download to file. The file can then be run by double clicking on the icon that is downloaded. The installation will then proceed.
If you get the Unix source make sure you compile in the tk extension if you want to use IDLE.
\section{Interactive Mode}
Go into IDLE (also called the Python GUI). You should see a window that has some text like this:
\begin{verbatim}
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
>>>
\end{verbatim}
The \verb'>>>' is Python way of telling you that you are in
interactive mode. In interactive mode what you type is immediately
run. Try typing \verb'1+1' in. Python will respond with \verb'2'.
Interactive mode allows you to test out and see what Python will do.
If you ever feel you need to play with new Python statements go into
interactive mode and try them out.
\section{Creating and Running Programs}
\label{create}
Go into IDLE if you are not already. Go to \verb'File' then \verb'New Window'. In this window type the following:
\begin{verbatim}
print "Hello, World!"
\end{verbatim}
First save the program. Go to \verb'File' then \verb'Save'. Save it as \file{hello.py}. (If you want you can save it to some other directory than the default.) Now that it is saved it can be run.
Next run the program by going to \verb'Run' then \verb'Run Module' (or if you have a older version of IDLE use \verb'Edit' then \verb'Run script'). This will output \verb'Hello, World!' on the \verb'*Python Shell*' window.
Confused still? Try this tutorial for IDLE at \url{http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html}
\section{Using Python from the command line}
If you don't want to use Python from the command line, you don't have too, just use IDLE. To get into interactive mode just type \verb'python' with out any arguments. To run a program create it with a text editor (Emacs has a good python mode) and then run it with \verb'python program name'.
%%Now for our first lesson, what is a computer program? A computer program is a set of very detailed instructions that tell a computer what to do.
%%TODO add section explaining how to run python programs
\chapter{Hello, World}
\section{What you should know}
You should know how to edit programs in a text editor or IDLE, save them to disk (floppy or hard) and run them once they have been saved.
\section{Printing}
Programming tutorials since the beginning of time have started with a little program called Hello, World! So here it is:
\begin{verbatim}
print "Hello, World!"
\end{verbatim}
If you are using the command line to run programs then type it in with a text editor, save it as \file{hello.py} and run it with \type{python hello.py}
Otherwise go into IDLE, create a new window, and create the program as
in section \ref{create}.
When this program is run here's what it prints:
\begin{verbatim}
Hello, World!
\end{verbatim}
Now I'm not going to tell you this every time, but when I show you a
program I recommend that you type it in and run it. I learn better
when I type it in and you probably do too.
Now here is a more complicated program:
\begin{verbatim}
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."
\end{verbatim}
When you run this program it prints out:
\begin{verbatim}
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.
\end{verbatim}
When the computer runs this program it first sees the line:
\begin{verbatim}
print "Jack and Jill went up a hill"
\end{verbatim}
so the computer prints:
\begin{verbatim}
Jack and Jill went up a hill
\end{verbatim}
Then the computer goes down to the next line and sees:
\begin{verbatim}
print "to fetch a pail of water;"
\end{verbatim}
So the computer prints to the screen:
\begin{verbatim}
to fetch a pail of water;
\end{verbatim}
The computer keeps looking at each line, follows the command and then goes on to the next line. The computer keeps running commands until it reaches the end of the program.
\section{Expressions}
Here is another program:
\begin{verbatim}
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
\end{verbatim}
And here is the output when the program is run:
\begin{verbatim}
2 + 2 is 4
3 * 4 is 12
99 = 100 - 1
(33 + 2) / 5 + 11.5 = 18.5
\end{verbatim}
As you can see Python can turn your thousand dollar computer into a 5 dollar calculator.
Python has six basic operations for numbers:
\begin{tabular}{l | c | l}
Operation & Symbol & Example \\
\hline
Exponentiation & \verb'**' & \verb'5 ** 2 == 25' \\
Multiplication & \verb'*' & \verb'2 * 3 == 6' \\
Division & \verb'/' & \verb'14 / 3 == 4' \\
Remainder & \verb'%' & \verb'14 % 3 == 2' \\
Addition & \verb'+' & \verb'1 + 2 == 3' \\
Subtraction & \verb'-' & \verb'4 - 3 == 1' \\
\end{tabular}
Notice that division follows the rule, if there are no decimals to start with, there will be no decimals to end with. (Note: This will be changing in Python 2.3) The following program shows this:
\begin{verbatim}
print "14 / 3 = ",14 / 3
print "14 % 3 = ",14 % 3
print
print "14.0 / 3.0 =",14.0 / 3.0
print "14.0 % 3.0 =",14 % 3.0
print
print "14.0 / 3 =",14.0 / 3
print "14.0 % 3 =",14.0 % 3
print
print "14 / 3.0 =",14 / 3.0
print "14 % 3.0 =",14 % 3.0
print
\end{verbatim}
With the output:
\begin{verbatim}
14 / 3 = 4
14 % 3 = 2
14.0 / 3.0 = 4.66666666667
14.0 % 3.0 = 2.0
14.0 / 3 = 4.66666666667
14.0 % 3 = 2.0
14 / 3.0 = 4.66666666667
14 % 3.0 = 2.0
\end{verbatim}
Notice how Python gives different answers for some problems depending on whether or not there decimal values are used.
The order of operations is the same as in math:
\begin{enumerate}
\item parentheses \verb'()'
\item exponents \verb'**'
\item multiplication \verb'*', division \verb'\', and remainder \verb'%'
\item addition \verb'+' and subtraction \verb'-'
\end{enumerate}
\section{Talking to humans (and other intelligent beings)}
Often in programming you are doing something complicated and may not in the future remember what you did. When this happens the program should probably be commented. A comment is a note to you and other programmers explaining what is happening. For example:
\begin{verbatim}
#Not quite PI, but an incredible simulation
print 22.0/7.0
\end{verbatim}
Notice that the comment starts with a \verb'#'. Comments are used to communicate with others who read the program and your future self to make clear what is complicated.
\section{Examples}
Each chapter (eventually) will contain examples of the programming features introduced in the chapter. You should at least look over them see if you understand them. If you don't, you may want to type them in and see what happens. Mess around them, change them and see what happens.
Denmark.py
\begin{verbatim}
print "Something's rotten in the state of Denmark."
print " -- Shakespeare"
\end{verbatim}
Output:
\begin{verbatim}
Something's rotten in the state of Denmark.
-- Shakespeare
\end{verbatim}
School.py
\begin{verbatim}
#This is not quite true outside of USA
# and is based on my dim memories of my younger years
print "Firstish Grade"
print "1+1 =",1+1
print "2+4 =",2+4
print "5-2 =",5-2
print
print "Thirdish Grade"
print "243-23 =",243-23
print "12*4 =",12*4
print "12/3 =",12/3
print "13/3 =",13/3," R ",13%3
print
print "Junior High"
print "123.56-62.12 =",123.56-62.12
print "(4+3)*2 =",(4+3)*2
print "4+3*2 =",4+3*2
print "3**2 =",3**2
print
\end{verbatim}
Output:
\begin{verbatim}
Firstish Grade
1+1 = 2
2+4 = 6
5-2 = 3
Thirdish Grade
243-23 = 220
12*4 = 48
12/3 = 4
13/3 = 4 R 1
Junior High
123.56-62.12 = 61.44
(4+3)*2 = 14
4+3*2 = 10
3**2 = 9
\end{verbatim}
\section{Exercises}
Write a program that prints your full name and your birthday as separate strings.
Write a program that shows the use of all 6 math functions.
\chapter{Who Goes There?}
\section{Input and Variables}
Now I feel it is time for a really complicated program. Here it is:
\begin{verbatim}
print "Halt!"
s = raw_input("Who Goes there? ")
print "You may pass,", s
\end{verbatim}
When {\bf I} ran it here is what {\bf my} screen showed:
\begin{verbatim}
Halt!
Who Goes there? Josh
You may pass, Josh
\end{verbatim}
Of course when you run the program your screen will look different
because of the \verb'raw_input' statement. When you ran the program
you probably noticed (you did run the program, right?) how you had to
type in your name and then press Enter. Then the program printed out
some more text and also your name. This is an example of input. The
program reaches a certain point and then waits for the user to input
some data that the program can use later.
Of course, getting information from the user would be useless if we didn't have anywhere to put that information and this is where variables come in. In the previous program {\tt s} is a variable. Variables are like a box that can store some piece of data. Here is a program to show examples of variables:
\begin{verbatim}
a = 123.4
b23 = 'Spam'
first_name = "Bill"
b = 432
c = a + b
print "a + b is", c
print "first_name is", first_name
print "Sorted Parts, After Midnight or",b23
\end{verbatim}
And here is the output:
\begin{verbatim}
a + b is 555.4
first_name is Bill
Sorted Parts, After Midnight or Spam
\end{verbatim}
Variables store data. The variables in the above program are {\tt a}, {\tt b23}, \verb'first_name', {\tt b}, and {\tt c}. The two basic types are strings and numbers. Strings are a sequence of letters, numbers and other characters. In this example {\tt b23} and \verb'first_name' are variables that are storing strings. {\tt Spam}, {\tt Bill}, {\tt a + b is}, and \verb'first_name is' are the strings in this program. The characters are surrounded by {\tt "} or {\tt '}. The other type of variables are numbers.
Okay, so we have these boxes called variables and also data that can go into the variable. The computer will see a line like \verb'first_name = "Bill"' and it reads it as Put the string {\tt Bill} into the box (or variable) \verb'first_name'. Later on it sees the statement {\tt c = a + b} and it reads it as Put {\tt a + b} or {\tt 123.4 + 432} or {\tt 555.4} into {\tt c}.
Here is another example of variable usage:
\begin{verbatim}
a = 1
print a
a = a + 1
print a
a = a * 2
print a
\end{verbatim}
And of course here is the output:
\begin{verbatim}
1
2
4
\end{verbatim}
Even if it is the same variable on both sides the computer still reads it as: First find out the data to store and than find out where the data goes.
One more program before I end this chapter:
\begin{verbatim}
num = input("Type in a Number: ")
str = raw_input("Type in a String: ")
print "num =", num
print "num is a ",type(num)
print "num * 2 =",num*2
print "str =", str
print "str is a ",type(str)
print "str * 2 =",str*2
\end{verbatim}
The output I got was:
\begin{verbatim}
Type in a Number: 12.34
Type in a String: Hello
num = 12.34
num is a <type 'float'>
num * 2 = 24.68
str = Hello
str is a <type 'string'>
str * 2 = HelloHello
\end{verbatim}
Notice that \verb'num' was gotten with {\tt input} while \verb'str' was gotten with \verb'raw_input'. \verb'raw_input' returns a string while {\tt input} returns a number. When you want the user to type in a number use {\tt input} but if you want the user to type in a string use \verb'raw_input'.
The second half of the program uses {\tt type} which tells what a
variable is. Numbers are of type {\tt int} or {\tt float} (which are
short for 'integer' and 'floating point' respectively). Strings are
of type {\tt string}. Integers and floats can be worked on by
mathematical functions, strings cannot. Notice how when python
multiples a number by a integer the expected thing happens. However
when a string is multiplied by a integer the string has that many
copies of it added i.e. \verb'str * 2 = HelloHello'.
The operations with strings do slightly different things than
operations with numbers. Here are some interative mode examples
to show that some more.
\begin{verbatim}
>>> "This"+" "+"is"+" joined."
'This is joined.'
>>> "Ha, "*5
'Ha, Ha, Ha, Ha, Ha, '
>>> "Ha, "*5+"ha!"
'Ha, Ha, Ha, Ha, Ha, ha!'
>>>
\end{verbatim}
Here is the list of some string operations:
\begin{tabular}{l | c | l}
Operation & Symbol & Example \\
\hline
Repetition & \verb'*' & \verb'"i"*5 == "iiiii"' \\
Concatenation & \verb'+' & \verb'"Hello, "+"World!" == "Hello, World!"' \\
\end{tabular}
%%n_1 = input("First Number? ")
%%n_2 = input("Second Number? ")
%%name = raw_input("Input your name:")
%%print name,", the sum of the first number and the second number is", n_1 + n_2
%%print "n_1 =",repr(n_1)
%%print "n_2 =",repr(n_2)
%%print "name =",repr(name)
%%\end{verbatim}
%%You use {\tt raw_input} when you want to get a string from the user. You use {\tt input} when you want to get a number.
\section{Examples}
Rate_times.py
\begin{verbatim}
#This programs calculates rate and distance problems
print "Input a rate and a distance"
rate = input("Rate:")
distance = input("Distance:")
print "Time:",distance/rate
\end{verbatim}
Sample runs:
\begin{verbatim}
> python rate_times.py
Input a rate and a distance
Rate:5
Distance:10
Time: 2
> python rate_times.py
Input a rate and a distance
Rate:3.52
Distance:45.6
Time: 12.9545454545
\end{verbatim}
Area.py
\label{firstarea}
\begin{verbatim}
#This program calculates the perimeter and area of a rectangle
print "Calculate information about a rectangle"
length = input("Length:")
width = input("Width:")
print "Area",length*width
print "Perimeter",2*length+2*width
\end{verbatim}
Sample runs:
\begin{verbatim}
> python area.py
Calculate information about a rectangle
Length:4
Width:3
Area 12
Perimeter 14
> python area.py
Calculate information about a rectangle
Length:2.53
Width:5.2
Area 13.156
Perimeter 15.46
\end{verbatim}
temperature.py
\begin{verbatim}
#Converts Fahrenheit to Celsius
temp = input("Farenheit temperature:")
print (temp-32.0)*5.0/9.0
\end{verbatim}
Sample runs:
\begin{verbatim}
> python temperature.py
Farenheit temperature:32
0.0
> python temperature.py
Farenheit temperature:-40
-40.0
> python temperature.py
Farenheit temperature:212
100.0
> python temperature.py
Farenheit temperature:98.6
37.0
\end{verbatim}
\section{Exercises}
Write a program that gets 2 string variables and 2 integer variables
from the user, concatenates (joins them together with no spaces) and
displays the strings, then multiplies the two numbers on a new line.
\chapter{Count to 10}
\section{While loops}
Presenting our first control structure. Ordinarily the computer starts with the first line and then goes down from there. Control structures change the order that statements are executed or decide if a certain statement will be run. Here's the source for a program that uses the while control structure:
\begin{verbatim}
a = 0
while a < 10:
a = a + 1
print a
\end{verbatim}
And here is the extremely exciting output:
\begin{verbatim}
1
2
3
4
5
6
7
8
9
10
\end{verbatim}
(And you thought it couldn't get any worse after turning your computer into a five dollar calculator?) So what does the program do? First it sees the line {\tt a = 0} and makes a zero. Then it sees {\tt while a < 10:} and so the computer checks to see if {\tt a < 10}. The first time the computer sees this statement a is zero so it is less than 10. In other words while a is less than ten the computer will run the tabbed in statements.
Here is another example of the use of {\tt while}:
\begin{verbatim}
a = 1
s = 0
print 'Enter Numbers to add to the sum.'
print 'Enter 0 to quit.'
while a != 0 :
print 'Current Sum:',s
a = input('Number? ')
s = s + a
print 'Total Sum =',s
\end{verbatim}
The first time I ran this program Python printed out:
\begin{verbatim}
File "sum.py", line 3
while a != 0
^
SyntaxError: invalid syntax
\end{verbatim}
I had forgotten to put the {\tt :} after the while. The error message complained about that problem and pointed out where it thought the problem was with the \verb*"^" . After the problem was fixed here was what I did with the program:
\begin{verbatim}
Enter Numbers to add to the sum.
Enter 0 to quit.
Current Sum: 0
Number? 200
Current Sum: 200
Number? -15.25
Current Sum: 184.75
Number? -151.85
Current Sum: 32.9
Number? 10.00
Current Sum: 42.9
Number? 0
Total Sum = 42.9
\end{verbatim}
Notice how {\tt print 'Total Sum =',s} is only run at the end. The {\tt while} statement only affects the line that are tabbed in (a.k.a.\ indented). The {\tt !=} means does not equal so {\tt while a != 0 :} means until a is zero run the tabbed in statements that are afterwards.
Now that we have while loops, it is possible to have programs that run forever. An easy way to do this is to write a program like this:
\begin{verbatim}
while 1 == 1:
print "Help, I'm stuck in a loop."
\end{verbatim}
This program will output {\tt Help, I'm stuck in a loop.} until the heat death of the universe or you stop it. The way to stop it is to hit the Control (or Ctrl) button and `c' (the letter) at the same time. This will kill the program. (Note: sometimes you will have to hit enter after the Control C.)
\section{Examples}
Fibonnacci.py
\begin{verbatim}
#This program calulates the fibonnacci sequence
a = 0
b = 1
count = 0
max_count = 20
while count < max_count:
count = count + 1
#we need to keep track of a since we change it
old_a = a
old_b = b
a = old_b
b = old_a + old_b
#Notice that the , at the end of a print statement keeps it
# from switching to a new line
print old_a,
print
\end{verbatim}
Output:
\begin{verbatim}
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
\end{verbatim}
Password.py
\begin{verbatim}
# Waits until a password has been entered. Use control-C to break out with out
# the password
#Note that this must not be the password so that the
# while loop runs at least once.
password = "foobar"
#note that != means not equal
while password != "unicorn":
password = raw_input("Password:")
print "Welcome in"
\end{verbatim}
Sample run:
\begin{verbatim}Password:auo
Password:y22
Password:password
Password:open sesame
Password:unicorn
Welcome in
\end{verbatim}
\chapter{Decisions}
\section{If statement}
As always I believe I should start each chapter with a warm up typing exercise so here is a short program to compute the absolute value of a number:
\begin{verbatim}
n = input("Number? ")
if n < 0:
print "The absolute value of",n,"is",-n
else:
print "The absolute value of",n,"is",n
\end{verbatim}
Here is the output from the two times that I ran this program:
\begin{verbatim}
Number? -34
The absolute value of -34 is 34
Number? 1
The absolute value of 1 is 1
\end{verbatim}
So what does the computer do when when it sees this piece of code? First it prompts the user for a number with the statement {\tt n = input("Number? ")}. Next it reads the line {\tt if n < 0:} If {\tt n} is less than zero Python runs the line {\tt print "The absolute value of",n,"is",-n}. Otherwise python runs the line {\tt print "The absolute value of",n,"is",n}.
More formally Python looks at whether the {\em expression} {\tt n < 0} is true or false. A {\tt if} statement is followed by a {\em block} of statements that are run when the expression is true. Optionally after the {\tt if} statement is a {\tt else} statement. The {\tt else} statement is run if the expression is false.
There are several different tests that an expression can have. Here is a table of all of them:
\begin{tabular}{l | l}
operator & function \\
\hline
\verb'<' & less than \\
\verb'<=' & less than or equal to \\
\verb'>' & greater than \\
\verb'>=' & greater than or equal to \\
\verb'==' & equal \\
\verb'!=' & not equal \\
\verb'<>' & another way to say not equal \\
\end{tabular}
Another feature of the {\tt if} command is the {\tt elif } statement. It stands for else if and means if the original {\tt if} statement is false and then the {\tt elif} part is true do that part. Here's an example:
\begin{verbatim}
a = 0
while a < 10:
a = a + 1
if a > 5:
print a," > ",5
elif a <= 7:
print a," <= ",7
else:
print "Neither test was true"
\end{verbatim}
and the output:
\begin{verbatim}
1 <= 7
2 <= 7
3 <= 7
4 <= 7
5 <= 7
6 > 5
7 > 5
8 > 5
9 > 5
10 > 5
\end{verbatim}
Notice how the {\tt elif a <= 7} is only tested when the {\tt if} statement fail to be true. {\tt elif} allows multiple tests to be done in a single if statement.
\section{Examples}
High_low.py
\label{firsthighlow}
\begin{verbatim}
#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 = 78
guess = 0
while guess != number :
guess = input ("Guess a number: ")
if guess > number :
print "Too high"
elif guess < number :
print "Too low"
print "Just right"
\end{verbatim}
Sample run:
\begin{verbatim}
Guess a number:100
Too high
Guess a number:50
Too low
Guess a number:75
Too low
Guess a number:87
Too high
Guess a number:81
Too high
Guess a number:78
Just right
\end{verbatim}
even.py
\begin{verbatim}
#Asks for a number.
#Prints if it is even or odd
number = input("Tell me a number: ")
if number % 2 == 0:
print number,"is even."
elif number % 2 == 1:
print number,"is odd."
else:
print number,"is very strange."
\end{verbatim}
Sample runs.
\begin{verbatim}
Tell me a number: 3
3 is odd.
Tell me a number: 2
2 is even.
Tell me a number: 3.14159
3.14159 is very strange.
\end{verbatim}
average1.py
\begin{verbatim}
#keeps asking for numbers until 0 is entered.
#Prints the average value.
count = 0
sum = 0.0
number = 1 #set this to something that will not exit
# the while loop immediatly.
print "Enter 0 to exit the loop"
while number != 0:
number = input("Enter a number:")
count = count + 1
sum = sum + number
count = count - 1 #take off one for the last number
print "The average was:",sum/count
\end{verbatim}
Sample runs
\begin{verbatim}
Enter 0 to exit the loop
Enter a number:3
Enter a number:5
Enter a number:0
The average was: 4.0
Enter 0 to exit the loop
Enter a number:1
Enter a number:4
Enter a number:3
Enter a number:0
The average was: 2.66666666667
\end{verbatim}
average2.py
\begin{verbatim}
#keeps asking for numbers until count have been entered.
#Prints the average value.
sum = 0.0
print "This program will take several numbers than average them"
count = input("How many numbers would you like to sum:")
current_count = 0
while current_count < count:
current_count = current_count + 1
print "Number ",current_count
number = input("Enter a number:")
sum = sum + number
print "The average was:",sum/count
\end{verbatim}
Sample runs
\begin{verbatim}
This program will take several numbers than average them
How many numbers would you like to sum:2
Number 1
Enter a number:3
Number 2
Enter a number:5
The average was: 4.0
This program will take several numbers than average them
How many numbers would you like to sum:3
Number 1
Enter a number:1
Number 2
Enter a number:4
Number 3
Enter a number:3
The average was: 2.66666666667
\end{verbatim}
%TODO: add another example
\section{Exercises}
Modify the password guessing program to keep track of how many times the
user has entered the password wrong. If it is more than 3 times, print
``That must have been complicated.''
Write a program that asks for two numbers. If the sum of the numbers
is greater than 100, print ``That is big number''.
Write a program that asks the user their name, if they enter your name
say "That is a nice name", if they enter "John Cleese" or "Michael
Palin", tell them how you feel about them ;), otherwise tell them "You
have a nice name".
\chapter{Debugging}
\section{What is debugging?}
\begin{quotation}
As soon as we started programming, we found to our surprise that it
wasn't as easy to get programs right as we had thought. Debugging had
to be discovered. I can remember the exact instant when I realized
that a large part of my life from then on was going to be spent in
finding mistakes in my own programs.
-- Maurice Wilkes discovers debugging, 1949
\end{quotation}
By now if you have been messing around with the programs you have probably found that sometimes the program does something you didn't want it to do. This is fairly common. Debugging is the process of figuring out what the computer is doing and then getting it to do what you want it to do. This can be tricky. I once spent nearly a week tracking down and fixing a bug that was caused by someone putting an {\tt x} where a {\tt y} should have been.
This chapter will be more abstract than previous chapters. Please tell me if
it is useful.
\section{What should the program do?}
The first thing to do (this sounds obvious) is to figure out what the
program should be doing if it is running correctly. Come up with some
test cases and see what happens. For example, let's say I have a
program to compute the perimeter of a rectangle (the sum of the length
of all the edges). I have the following test cases:
\begin{tabular}{l | l | l}
width & height & perimeter\\
\hline
3 & 4 & 14\\
\hline
2 & 3 & 10\\
\hline
4 & 4 & 16\\
\hline
2 & 2 & 8\\
\hline
5 & 1 & 12\\
\end{tabular}
I now run my program on all of the test cases and see if the program does what
I expect it to do. If it doesn't then I need to find out what the computer is
doing.
More commonly some of the test cases will work and some will not. If that is the case you should try and figure out what the working ones have in common.
For example here is the output for a perimeter program (you get to see the code in a minute):
\begin{verbatim}
Height: 3
Width: 4
perimeter = 15
\end{verbatim}
\begin{verbatim}
Height: 2
Width: 3
perimeter = 11
\end{verbatim}
\begin{verbatim}
Height: 4
Width: 4
perimeter = 16
\end{verbatim}
\begin{verbatim}
Height: 2
Width: 2
perimeter = 8
\end{verbatim}
\begin{verbatim}
Height: 5
Width: 1
perimeter = 8
\end{verbatim}
Notice that it didn't work for the first two inputs, it worked for the next
two and it didn't work on the last one. Try and figure out what is in common
with the working ones. Once you have some idea what the problem is finding the
cause is easier. With your own programs you should try more test cases if you need them.
\section{What does the program do?}
The next thing to do is to look at the source code. One of the most important things to do while programming is reading source code. The primary way to do this is code walkthroughs.
A code walkthrough starts at the first line, and works its way down until the program is done. {\tt While} loops and {\tt if} statements mean that some lines may never be run and some lines are run many times. At each line you figure out what Python has done.
Lets start with the simple perimeter program. Don't type it in, you are going to read it, not run it. The source code is:
\begin{verbatim}
height = input("Height: ")
width = input("Width: ")
print "perimeter = ",width+height+width+width
\end{verbatim}
\question What is the first line Python runs?
\answer The first line is alway run first. In this case it is: \verb'height = input("Height: ")'
\question What does that line do?
\answer Prints {\tt Height: }, waits for the user to type a number in, and puts that in the variable height.
\question What is the next line that runs?
\answer In general, it is the next line down which is: \verb'width = input("Width: ")'
\question What does that line do?
\answer Prints {\tt Width: }, waits for the user to type a number in, and puts what the user types in the variable width.
\question What is the next line that runs?
\answer When the next line is not indented more or less than the current line,
it is the line right afterwards, so it is: \verb'print "perimeter = ",width+height+width+width' (It may also run a function in the current line, but thats a future chapter.)
\question What does that line do?
\answer First it prints {\tt perimeter =}, then it prints {\tt width+height+width+width}.
\question Does {\tt width+height+width+width} calculate the perimeter properly?
\answer Let's see, perimeter of a rectangle is the bottom (width) plus the left side (height) plus the top (width) plus the right side (huh?). The last item should be the right side's length, or the height.
\question Do you understand why some of the times the perimeter was calculated `correctly'?
\answer It was calculated correctly when the width and the height were equal.
The next program we will do a code walkthrough for is a program that is supposed to print out 5 dots on the screen. However, this is what the program is outputting:
\begin{verbatim}
. . . .
\end{verbatim}
And here is the program:
\begin{verbatim}
number = 5
while number > 1:
print ".",
number = number - 1
print
\end{verbatim}
This program will be more complex to walkthrough since it now has indented portions (or control structures). Let us begin.
\question What is the first line to be run?
\answer The first line of the file: {\tt number = 5}
\question What does it do?
\answer Puts the number 5 in the variable number.
\question What is the next line?
\answer The next line is: {\tt while number > 1:}
\question What does it do?
\answer Well, {\tt while} statements in general look at their expression, and if it is true they do the next indented block of code, otherwise they skip the next indented block of code.
\question So what does it do right now?
\answer If {\tt number > 1} is true then the next two lines will be run.
\question So is {\tt number > 1}?
\answer The last value put into {\tt number} was {\tt 5} and {\tt 5 > 1} so yes.
\question So what is the next line?
\answer Since the {\tt while} was true the next line is: \verb'print ".",'
\question What does that line do?
\answer Prints one dot and since the statement ends with a {\tt ,} the next print statement will not be on a different screen line.
\question What is the next line?
\answer \verb'number = number - 1' since that is following line and there are no indent changes.
\question What does it do?
\answer It calculates {\tt number - 1}, which is the current value of
{\tt number} (or 5) subtracts 1 from it, and makes that the new value
of number. So basically it changes {\tt number}'s value from 5 to 4.
\question What is the next line?
\answer Well, the indent level decreases so we have to look at what type of control structure it is. It is a {\tt while} loop, so we have to go back to the {\tt while} clause which is \verb'while number > 1:'
\question What does it do?
\answer It looks at the value of number, which is 4, and compares it to 1 and since \verb'4 > 1' the while loop continues.
\question What is the next line?
\answer Since the while loop was true, the next line is: \verb'print ".",'
\question What does it do?
\answer It prints a second dot on the line.
\question What is the next line?
\answer No indent change so it is: \verb'number = number - 1'
\question And what does it do?
\answer It talks the current value of number (4), subtracts 1 from it, which gives it 3 and then finally makes 3 the new value of number.
\question What is the next line?
\answer Since there is an indent change caused by the end of the while loop, the next line is: \verb'while number > 1:'
\question What does it do?
\answer It compares the current value of number (3) to 1. \verb'3 > 1' so the while loop continues.
\question What is the next line?
\answer Since the while loop condition was true the next line is: \verb'print ".",'
\question And it does what?
\answer A third dot is printed on the line.
\question What is the next line?
\answer It is: \verb'number = number - 1'
\question What does it do?
\answer It takes the current value of number (3) subtracts from it 1 and makes the 2 the new value of number.
\question What is the next line?
\answer Back up to the start of the while loop: \verb'while number > 1:'
\question What does it do?
\answer It compares the current value of number (2) to 1. Since \verb'2 > 1' the while loop continues.
\question What is the next line?
\answer Since the while loop is continuing: \verb'print ".",'
\question What does it do?
\answer It discovers the meaning of life, the universe and everything. I'm joking. (I had to make sure you were awake.) The line prints a fourth dot on the screen.
\question What is the next line?
\answer It's: \verb'number = number - 1'
\question What does it do?
\answer Takes the current value of number (2) subtracts 1 and makes 1 the new value of number.
\question What is the next line?
\answer Back up to the while loop: \verb'while number > 1:'
\question What does the line do?
\answer It compares the current value of number (1) to 1. Since \verb'1 > 1' is false (one is not greater than one), the while loop exits.
\question What is the next line?
\answer Since the while loop condition was false the next line is the line after the while loop exits, or: \verb'print'
\question What does that line do?
\answer Makes the screen go to the next line.
\question Why doesn't the program print 5 dots?
\answer The loop exits 1 dot too soon.
\question How can we fix that?
\answer Make the loop exit 1 dot later.
\question And how do we do that?
\answer There are several ways. One way would be to change the while loop to:
\verb'while number > 0:' Another way would be to change the conditional to: \verb'number >= 1' There are a couple others.
\section{How do I fix the program?}
You need to figure out what the program is doing. You need to figure out what the program should do. Figure out what the difference between the two is. Debugging is a skill that has to be done to be learned. If you can't figure it out after an hour or so take a break, talk to someone about the problem or contemplate the lint in your navel. Come back in a while and you will probably have new ideas about the problem. Good luck.
%%TODO: add code walkthrough for dots.py
\chapter{Defining Functions}
\section{Creating Functions}
To start off this chapter I am going to give you an example of what you could do but shouldn't (so don't type it in):
\begin{verbatim}
a = 23
b = -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"
\end{verbatim}
with the output being:
\begin{verbatim}
The absolute values of 23 and 23 are equal
\end{verbatim}
The program seems a little repetitive. (Programmers hate to repeat things (That's what computers are for aren't they?)) Fortunately Python allows you to create functions to remove duplication. Here's the rewritten example:
\begin{verbatim}
a = 23
b = -23
def my_abs(num):
if num < 0:
num = -num
return num
if my_abs(a) == my_abs(b):
print "The absolute values of", a,"and",b,"are equal"
else:
print "The absolute values of a and b are different"
\end{verbatim}
with the output being:
\begin{verbatim}
The absolute values of 23 and -23 are equal
\end{verbatim}
The key feature of this program is the {\tt def} statement. {\tt def}
(short for define) starts a function definition. {\tt def} is
followed by the name of the function {\tt my_abs}. Next comes a {\tt (}
followed by the parameter {\tt num} ({\tt num} is passed from the
program into the function when the function is called). The statements
after the {\tt :} are executed when the function is used. The
statements continue until either the indented statements end or a
{\tt return} is encountered. The {\tt return} statement returns a value
back to the place where the function was called.
Notice how the values of {\tt a} and {\tt b} are not changed.
Functions of course can be used to repeat tasks that don't return
values. Here's some examples:
\begin{verbatim}
def hello():
print "Hello"
def area(width,height):
return width*height
def print_welcome(name):
print "Welcome",name
hello()
hello()
print_welcome("Fred")
w = 4
h = 5
print "width =",w,"height =",h,"area =",area(w,h)
\end{verbatim}
with output being:
\begin{verbatim}
Hello
Hello
Welcome Fred
width = 4 height = 5 area = 20
\end{verbatim}
That example just shows some more stuff that you can do with
functions. Notice that you can use no arguments or two or more.
Notice also when a function doesn't need to send back a value, a
return is optional.
%Functions can be used to eliminate repeat code.
\section{Variables in functions}
Of course, when eliminiating repeated code, you often have variables in
the repeated code. These are dealt with in a special way in Python. Up
till now, all variables we have see are global variables. Functions have
a special type of variable called local variables. These variables only
exist while the function is running. When a local variable has the
same name as another variable such as a global variable, the local variable
hides the other variable. Sound confusing? Well, hopefully this next
example (which is a bit contrived) will clear things up.
\begin{verbatim}
a_var = 10
b_var = 15
e_var = 25
def a_func(a_var):
print "in a_func a_var = ",a_var
b_var = 100 + a_var
d_var = 2*a_var
print "in a_func b_var = ",b_var
print "in a_func d_var = ",d_var
print "in a_func e_var = ",e_var
return b_var + 10
c_var = a_func(b_var)
print "a_var = ",a_var
print "b_var = ",b_var
print "c_var = ",c_var
print "d_var = ",d_var
\end{verbatim}
The output is:
\begin{verbatim}
in a_func a_var = 15
in a_func b_var = 115
in a_func d_var = 30
in a_func e_var = 25
a_var = 10
b_var = 15
c_var = 125
d_var =
Traceback (innermost last):
File "separate.py", line 20, in ?
print "d_var = ",d_var
NameError: d_var
\end{verbatim}
In this example the variables {\tt a_var}, {\tt b_var}, and {\tt d_var}
are all local variables when they are inside the function {\tt a_func}.
After the statement {\tt return b_var + 10} is run, they all cease to
exist. The variable {\tt a_var} is automatically a local variable since it
is a parameter name. The variables {\tt b_var} and {\tt d_var} are local
variables since they appear on the left of an equals sign in the function in
the statements \verb'b_var = 100 + a_var' and \verb'd_var = 2*a_var' .
Inside of the function {\tt a_var} is 15 since the function is called
with {\tt a_func(b_var)}. Since at that point in time {\tt b_var} is
15, the call to the function is {\tt a_func(15)} This ends up setting
{\tt a_var} to 15 when it is inside of {\tt a_func}.
As you can see, once the function finishes running, the local variables
{\tt a_var} and {\tt b_var} that had hidden the global variables of the same
name are gone. Then the statement \verb'print "a_var = ",a_var' prints the
value {\tt 10} rather than the value {\tt 15} since the local variable
that hid the global variable is gone.
Another thing to notice is the {\tt NameError} that happens at the end.
This appears since the variable {\tt d_var} no longer exists since
{\tt a_func} finished. All the local variables are deleted when the function
exits. If you want to get something from a function, then you will have
to use {\tt return something}.
One last thing to notice is that the value of {\tt e_var} remains unchanged
inside {\tt a_func} since it is not a parameter and it never appears on the
left of an equals sign inside of the function {\tt a_func}. When a
global variable is accessed inside a function it is the global variable
from the outside.
Functions allow local variables that exist only inside the function and
can hide other variables that are outside the function.
\section{Function walkthrough}
{\em TODO} Move this section to a new chapter, Advanced Functions.
Now we will do a walk through for the following program:
\begin{verbatim}
def mult(a,b):
if b == 0:
return 0
rest = mult(a,b - 1)
value = a + rest
return value
print "3*2 = ",mult(3,2)
\end{verbatim}
Basically this program creates a positive integer multiplication function
(that is far slower than the built in multiplication function) and then
demonstrates this function with a use of the function.
\question What is the first thing the program does?
\answer The first thing done is the function mult is defined with the lines:
\begin{verbatim}
def mult(a,b):
if b == 0:
return 0
rest = mult(a,b - 1)
value = a + rest
return value
\end{verbatim}
This creates a function that takes two parameters and returns a value when
it is done. Later this function can be run.
\question What happens next?
\answer The next line after the function,
\verb'print "3*2 = ",mult(3,2)' is run.
\question And what does this do?
\answer It prints \verb'3*2 = ' and the return value of \verb'mult(3,2)'
\question And what does \verb'mult(3,2)' return?
\answer We need to do a walkthrough of the {\tt mult} function to find out.
\question What happens next?
\answer The variable {\tt a} gets the value 3 assigned to it and the
variable {\tt b} gets the value 2 assigned to it.
\question And then?
\answer The line \verb'if b == 0:' is run. Since {\tt b} has the value 2
this is false so the line \verb' return 0' is skipped.
\question And what then?
\answer The line \verb'rest = mult(a,b - 1)' is run. This line sets the
local variable {\tt rest} to the value of \verb'mult(a,b - 1)'. The
value of {\tt a} is 3 and the value of {\tt b} is 2 so the function call
is \verb'mult(3,1)'
\question So what is the value of \verb'mult(3,1)' ?
\answer We will need to run the function {\tt mult} with the parameters
3 and 1.
\question So what happens next?
\answer The local variables in the {\em new} run of the function are
set so that {\tt a} has the value 3 and {\tt b} has the value 1.
Since these are local values these do not affect the previous values
of {\tt a} and {\tt b}.
\question And then?
\answer Since {\tt b} has the value 1 the if statement is false, so the
next line becomes \verb'rest = mult(a,b - 1)'.
\question What does this line do?
\answer This line will assign the value of {\tt mult(3,0)} to rest.
\question So what is that value?
\answer We will have to run the function one more time to find that out.
This time {\tt a} has the value 3 and {\tt b} has the value 0.
\question So what happens next?
\answer The first line in the function to run is \verb'if b == 0:' . {\tt b} has the value 0 so the next line to run is \verb'return 0'
\question And what does the line \verb'return 0' do?
\answer This line returns the value 0 out of the function.
\question So?
\answer So now we know that {\tt mult(3,0)} has the value 0. Now we
know what the line \verb'rest = mult(a,b - 1)' did since we have run
the function {\tt mult} with the parameters 3 and 0. We have finished
running {\tt mult(3,0)} and are now back to running {\tt mult(3,1)}.
The variable {\tt rest} gets assigned the value 0.
\question What line is run next?
\answer The line \verb'value = a + rest' is run next. In this run of the
function, \verb'a=3' and \verb'rest=0' so now \verb'value=3'.
\question What happens next?
\answer The line \verb'return value' is run. This returns 3 from the function.
This also exits from the run of the function {\tt mult(3,1)}. After {\tt return} is called, we go back to running {\tt mult(3,2)}.
\question Where were we in {\tt mult(3,2)}?
\answer We had the variables \verb'a=3' and \verb'b=2' and were examining
the line \verb'rest = mult(a,b - 1)' .
\question So what happens now?
\answer The variable {\tt rest} get 3 assigned to it. The next line
\verb'value = a + rest' sets {\tt value} to {\tt 3+3} or 6.
\question So now what happens?
\answer The next line runs, this returns 6 from the function. We are now
back to running the line \verb'print "3*2 = ",mult(3,2)' which can now
print out the 6.
\question What is happening overall?
\answer Basically we used two facts to calulate the multipule of the
two numbers. The first is that any number times 0 is 0 ({\tt x * 0 =
0}). The second is that a number times another number is equal to the
first number plus the first number times one less than the second
number ({\tt x * y = x + x * (y - 1)}). So what happens is {\tt 3*2} is
first converted into {\tt 3 + 3*1}. Then {\tt 3*1} is converted into
{\tt 3 + 3*0}. Then we know that any number times 0 is 0 so {\tt 3*0}
is 0. Then we can calculate that {\tt 3 + 3*0} is {\tt 3 + 0} which
is {\tt 3}. Now we know what {\tt 3*1} is so we can calculate that
{\tt 3 + 3*1} is {\tt 3 + 3} which is {\tt 6}.
This is how the whole thing works:
\begin{verbatim}
3*2
3 + 3*1
3 + 3 + 3*0
3 + 3 + 0
3 + 3
6
\end{verbatim}
These last two sections were recently written. If you have any
comments, found any errors or think I need more/clearer explanations
please email. I have been known in the past to make simple things
incomprehensible. If the rest of the tutorial has made sense, but this
section didn't, it is probably my fault and I would like to know.
Thanks.
\section{Examples}
factorial.py
\begin{verbatim}
#defines a function that calculates the factorial
def factorial(n):
if n <= 1:
return 1
return n*factorial(n-1)
print "2! = ",factorial(2)
print "3! = ",factorial(3)
print "4! = ",factorial(4)
print "5! = ",factorial(5)
\end{verbatim}
Output:
\begin{verbatim}
2! = 2
3! = 6
4! = 24
5! = 120
\end{verbatim}
temperature2.py
\begin{verbatim}
#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(temp)
elif choice == "f":
temp = input("Fahrenheit temperature:")
print "Celsius:",fahrenheit_to_celsius(temp)
elif choice != "q":
print_options()
choice = raw_input("option:")
\end{verbatim}
Sample Run:
\begin{verbatim}
> python temperature2.py
Options:
'p' print options
'c' convert from celsius
'f' convert from fahrenheit
'q' quit the program
option:c
Celsius temperature:30
Fahrenheit: 86.0
option:f
Fahrenheit temperature:60
Celsius: 15.5555555556
option:q
\end{verbatim}
area2.py
\begin{verbatim}
#By Amos Satterlee
print
def 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)
print
print 'To find the area of a rectangle,'
print 'Enter the width and height below.'
print
w = 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)
\end{verbatim}
Sample Run:
\begin{verbatim}
Your Name: Josh
Hello!
Welcome, Josh
To find the area of a rectangle,
Enter the width and height below.
Width: -4
Must be a positive number
Width: 4
Height: 3
Width = 4 Height = 3 so Area = 12
\end{verbatim}
\section{Exercises}
Rewrite the area.py program done in \ref{firstarea} to have a separate
function for the area of a square, the area of a rectangle, and the
area of a circle. (3.14 * radius**2). This program should include a
menu interface.
\chapter{Lists}
\section{Variables with more than one value}
You have already seen ordinary variables that store a single value. However other variable types can hold more than one value. The simplest type is called a list. Here is an example of a list being used:
\begin{verbatim}
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]
\end{verbatim}
and a output example:
\begin{verbatim}
What month (1-12)? 3
The month is March
\end{verbatim}
In this example the {\tt months} is a list. {\tt months} is defined with the lines {\tt months = ['January', 'February', 'March', 'April', 'May', 'June', 'July',\verb'\' 'August', 'September', 'October', 'November', 'December']} (Note that a \verb'\' can be used to split a long line). The \verb'[' and \verb']' start and end the list with comma's (``\verb',''') separating the list items. The list is used in \verb'months[which_one - 1]'. A list consists of items that are numbered starting at 0. In other words if you wanted January you would use {\tt months[0]}. Give a list a number and it will return the value that is stored at that location.
The statement {\tt if 1 <= which_one <= 12:} will only be true if {\tt which_one} is between one and twelve inclusive (in other words it is what you would expect if you have seen that in algebra).
Lists can be thought of as a series of boxes. %Each box has a different value.
For example, the boxes created by {\tt demolist = ['life',42, 'the universe', 6,'and',7]} would look like this:
\begin{tabular}{l | c | c | c | c | c | c |}
box number & 0 & 1 & 2 & 3 & 4 & 5 \\
\hline
demolist & `life' & 42 & `the universe' & 6 & `and' & 7\\
\hline
\end{tabular}
Each box is referenced by its number so the statement {\tt demolist[0]} would get {\tt 'life'}, {\tt demolist[1]} would get {\tt 42} and so on up to {\tt demolist[5]} getting {\tt 7}.
\section{More features of lists}
The next example is just to show a lot of other stuff lists can do (for once I don't expect you to type it in, but you should probably play around with lists until you are comfortable with them.). Here goes:
\begin{verbatim}
demolist = ['life',42, 'the universe', 6,'and',7]
print 'demolist = ',demolist
demolist.append('everything')
print "after 'everything' was appended demolist is now:"
print demolist
print 'len(demolist) =', len(demolist)
print 'demolist.index(42) =',demolist.index(42)
print 'demolist[1] =', demolist[1]
#Next we will loop through the list
c = 0
while c < len(demolist):
print 'demolist[',c,']=',demolist[c]
c = c + 1
del demolist[2]
print "After 'the universe' was removed demolist is now:"
print demolist
if '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
\end{verbatim}
The output is:
\begin{verbatim}
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) = 7
demolist.index(42) = 1
demolist[1] = 42
demolist[ 0 ]= life
demolist[ 1 ]= 42
demolist[ 2 ]= the universe
demolist[ 3 ]= 6
demolist[ 4 ]= and
demolist[ 5 ]= 7
demolist[ 6 ]= everything
After 'the universe' was removed demolist is now:
['life', 42, 6, 'and', 7, 'everything']
'life' was found in demolist
'amoeba' was not found in demolist
The sorted demolist is [6, 7, 42, 'and', 'everything', 'life']
\end{verbatim}
This example uses a whole bunch of new functions. Notice that you can
just {\tt print} a whole list. Next the {\tt append} function is used
to add a new item to the end of the list. \verb'len' returns how many
items are in a list. The valid indexes (as in numbers that can be
used inside of the []) of a list range from 0 to {\tt len - 1}. The
{\tt index} function tell where the first location of an item is
located in a list. Notice how \verb'demolist.index(42)' returns 1 and
when \verb'demolist[1]' is run it returns 42. The line
\verb'#Next we will loop through the list' is a just a reminder to the
programmer (also called a comment). Python will ignore any lines that
start with a \verb'#'. Next the lines:
\begin{verbatim}
c = 0
while c < len(demolist):
print 'demolist[',c,']=',demolist[c]
c = c + 1
\end{verbatim}
Create a variable {\tt c} which starts at 0 and is incremented until it reaches the last index of the list. Meanwhile the {\tt print} statement prints out each element of the list.
The \verb'del' command can be used to remove a given element in a list. The next few lines use the {\tt in} operator to test if an element is in or is not in a list.
The \verb'sort' function sorts the list. This is useful if you need a
list in order from smallest number to largest or alphabetical. Note
that this rearranges the list.
In summary for a list the following operations occur:
\begin{tabular}{l | l}
example & explanation\\
\hline
{\tt list[2]} & accesses the element at index 2\\
{\tt list[2] = 3} & sets the element at index 2 to be 3\\
{\tt del list[2] } & removes the element at index 2\\
{\tt len(list)} & returns the length of list\\
{\tt "value" in list} & is true if {\tt "value"} is an element in list\\
{\tt "value" not in list} & is true if {\tt "value"} is not an element in list\\
{\tt list.sort()} & sorts list\\
{\tt list.index("value")} & returns the index of the first place that {\tt "value"} occurs\\
{\tt list.append("value")} & adds an element {\tt "value"} at the end of the list\\
\end{tabular}
This next example uses these features in a more useful way:
\begin{verbatim}
menu_item = 0
list = []
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 = 0
if 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]
#The code above only removes the first occurance of
# the name. The code below from Gerald removes all.
#while 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"
\end{verbatim}
And here is part of the output:
\begin{verbatim}
--------------------
1. Print the list
2. Add a name to the list
3. Remove a name from the list
4. Change an item in the list
9. Quit
Pick an item from the menu: 2
Type in a name to add: Jack
Pick an item from the menu: 2
Type in a name to add: Jill
Pick an item from the menu: 1
0 . Jack
1 . Jill
Pick an item from the menu: 3
What name would you like to remove: Jack
Pick an item from the menu: 4
What name would you like to change: Jill
What is the new name: Jill Peters
Pick an item from the menu: 1
0 . Jill Peters
Pick an item from the menu: 9
Goodbye
\end{verbatim}
That was a long program. Let's take a look at the source code. The line {\tt list = []} makes the variable {\tt list} a list with no items (or elements). The next important line is \verb'while menu_item != 9:'. This line starts a loop that allows the menu system for this program. The next few lines display a menu and decide which part of the program to run.
The section:
\begin{verbatim}
current = 0
if len(list) > 0:
while current < len(list):
print current,". ",list[current]
current = current + 1
else:
print "List is empty"
\end{verbatim}
goes through the list and prints each name. \verb'len(list_name)' tell how many items are in a list. If {\tt len} returns \verb'0' then the list is empty.
Then a few lines later the statement {\tt list.append(name)} appears. It uses the {\tt append} function to add a item to the end of the list. Jump down another two lines and notice this section of code:
\begin{verbatim}
item_number = list.index(del_name)
del list[item_number]
\end{verbatim}
Here the {\tt index} function is used to find the index value that will be used later to remove the item. \verb'del list[item_number]' is used to remove an element of the list.
The next section
\begin{verbatim}
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"
\end{verbatim}
uses {\tt index} to find the \verb'item_number' and then puts \verb'new_name' where the \verb'old_name' was.
Congraduations, with lists under your belt, you now know enough of the language
that you could do any computations that a computer can do (this is technically known as Turing-Completness). Of course, there are still many features that
are used to make your life easier. %%%TODO.
\section{Examples}
test.py
\begin{verbatim}
## This program runs a test of knowledge
true = 1
false = 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 lists
return [["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"]]
\end{verbatim}
\begin{verbatim}
# This will test a single question
# it takes a single question in
# it returns true if the user typed the correct answer, otherwise false
def check_question(question_and_answer):
#extract the question and the answer from the list
question = question_and_answer[0]
answer = question_and_answer[1]
# give the question to the user
given_answer = raw_input(question)
# compare the user's answer to the testers answer
if answer == given_answer:
print "Correct"
return true
else:
print "Incorrect, correct was:",answer
return false
\end{verbatim}
\begin{verbatim}
# This will run through all the questions
def run_test(questions):
if len(questions) == 0:
print "No questions were given."
# the return exits the function
return
index = 0
right = 0
while index < len(questions):
#Check the question
if check_question(questions[index]):
right = right + 1
#go to the next question
index = index + 1
#notice the order of the computation, first multiply, then divide
print "You got ",right*100/len(questions),"% right out of",len(questions)
#now lets run the questions
run_test(get_questions())
\end{verbatim}
Sample Output:
\begin{verbatim}
What color is the daytime sky on a clear day?green
Incorrect, correct was: blue
What is the answer to life, the universe and everything?42
Correct
What is a three letter word for mouse trap?cat
Correct
You got 66 % right out of 3
\end{verbatim}
\section{Exercises}
Expand the test.py program so it has menu giving the option of taking
the test, viewing the list of questions and answers, and an option to
Quit. Also, add a new question to ask, "What noise does a truly
advanced machine make?" with the answer of "ping".
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\chapter{For Loops}
And here is the new typing exercise for this chapter:
\begin{verbatim}
onetoten = range(1,11)
for count in onetoten:
print count
\end{verbatim}
and the ever-present output:
\begin{verbatim}
1
2
3
4
5
6
7
8
9
10
\end{verbatim}
The output looks awfully familiar but the program code looks different. The first line uses the {\tt range} function. The {\tt range} function uses two arguments like this {\tt range(start,finish)}. {\tt start} is the first number that is produced. {\tt finish} is one larger than the last number. Note that this program could have been done in a shorter way:
\begin{verbatim}
for count in range(1,11):
print count
\end{verbatim}
Here are some examples to show what happens with the {\tt range} command:
\begin{verbatim}
>>> 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)
[]
\end{verbatim}
The next line \verb'for count in onetoten:' uses the {\tt for} control structure. A {\tt for} control structure looks like {\tt for variable in list:}. {\tt list} is gone through starting with the first element of the list and going to the last. As {\tt for} goes through each element in a list it puts each into {\tt variable}. That allows {\tt variable} to be used in each successive time the for loop is run through. Here is another example (you don't have to type this) to demonstrate:
\begin{verbatim}
demolist = ['life',42, 'the universe', 6,'and',7,'everything']
for item in demolist:
print "The Current item is:",
print item
\end{verbatim}
The output is:
\begin{verbatim}
The Current item is: life
The Current item is: 42
The Current item is: the universe
The Current item is: 6
The Current item is: and
The Current item is: 7
The Current item is: everything
\end{verbatim}
Notice how the for loop goes through and sets item to each element in the list. (Notice how if you don't want {\tt print} to go to the next line add a comma at the end of the statement (i.e. if you want to print something else on that line). ) So, what is {\tt for} good for? (groan) The first use is to go through all the elements of a list and do something with each of them. Here a quick way to add up all the elements:
\begin{verbatim}
list = [2,4,6,8]
sum = 0
for num in list:
sum = sum + num
print "The sum is: ",sum
\end{verbatim}
with the output simply being:
\begin{verbatim}
The sum is: 20
\end{verbatim}
Or you could write a program to find out if there are any duplicates in a list like this program does:
\begin{verbatim}
list = [4, 5, 7, 8, 9, 1,0,7,10]
list.sort()
prev = list[0]
del list[0]
for item in list:
if prev == item:
print "Duplicate of ",prev," Found"
prev = item
\end{verbatim}
and for good measure:
\begin{verbatim}
Duplicate of 7 Found
\end{verbatim}
Okay, so how does it work? Here is a special debugging version to help you understand (you don't need to type this in):
\begin{verbatim}
l = [4, 5, 7, 8, 9, 1,0,7,10]
print "l = [4, 5, 7, 8, 9, 1,0,7,10]","\tl:",l
l.sort()
print "l.sort()","\tl:",l
prev = l[0]
print "prev = l[0]","\tprev:",prev
del l[0]
print "del l[0]","\tl:",l
for item in l:
if prev == item:
print "Duplicate of ",prev," Found"
print "if prev == item:","\tprev:",prev,"\titem:",item
prev = item
print "prev = item","\t\tprev:",prev,"\titem:",item
\end{verbatim}
with the output being:
\begin{verbatim}
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: 0
del l[0] l: [1, 4, 5, 7, 7, 8, 9, 10]
if prev == item: prev: 0 item: 1
prev = item prev: 1 item: 1
if prev == item: prev: 1 item: 4
prev = item prev: 4 item: 4
if prev == item: prev: 4 item: 5
prev = item prev: 5 item: 5
if prev == item: prev: 5 item: 7
prev = item prev: 7 item: 7
Duplicate of 7 Found
if prev == item: prev: 7 item: 7
prev = item prev: 7 item: 7
if prev == item: prev: 7 item: 8
prev = item prev: 8 item: 8
if prev == item: prev: 8 item: 9
prev = item prev: 9 item: 9
if prev == item: prev: 9 item: 10
prev = item prev: 10 item: 10
\end{verbatim}
The reason I put so many {\tt print} statements in the code was so that you can see what is happening in each line. (BTW, if you can't figure out why a program is not working, try putting in lots of print statements to you can see what is happening) First the program starts with a boring old list. Next the program sorts the list. This is so that any duplicates get put next to each other. The program then initializes a prev(ious) variable. Next the first element of the list is deleted so that the first item is not incorrectly thought to be a duplicate. Next a for loop is gone into. Each item of the list is checked to see if it is the same as the previous. If it is a duplicate was found. The value of prev is then changed so that the next time the for loop is run through prev is the previous item to the current. Sure enough, the 7 is found to be a duplicate. (Notice how \verb'\t' is used to print a tab.)
The other way to use for loops is to do something a certain number of times. Here is some code to print out the first 11 numbers of the Fibonacci series:
\begin{verbatim}
a = 1
b = 1
for c in range(1,10):
print a,
n = a + b
a = b
b = n
\end{verbatim}
with the surprising output:
\begin{verbatim}
1 1 2 3 5 8 13 21 34
\end{verbatim}
Everything that can be done with {\tt for} loops can also be done with {\tt while} loops but {\tt for} loops give an easy way to go through all the elements in a list or to do something a certain number of times.
\chapter{Boolean Expressions}
Here is a little example of boolean expressions (you don't have to type it in):
\begin{verbatim}
a = 6
b = 7
c = 42
print 1, a == 6
print 2, a == 7
print 3,a == 6 and b == 7
print 4,a == 7 and b == 7
print 5,not a == 7 and b == 7
print 6,a == 7 or b == 7
print 7,a == 7 or b == 6
print 8,not (a == 7 and b == 6)
print 9,not a == 7 and b == 6
\end{verbatim}
With the output being:
\begin{verbatim}
1 1
2 0
3 1
4 0
5 1
6 1
7 0
8 1
9 0
\end{verbatim}
What is going on? The program consists of a bunch of funny looking {\tt print} statements. Each {\tt print} statement prints a number and an expression. The number is to help keep track of which statement I am dealing with. Notice how each expression ends up being either 0 or 1. In Python false is written as 0 and true is written as 1.
%%For example:
%%\begin{verbatim}
%%>>> if 1:
%%... print "true"
%%... else:
%%... print "false"
%%...
%%true
%%>>> if 0:
%%... print "true"
%%... else:
%%... print "false"
%%...
%%false
%%\end{verbatim}
The lines:
\begin{verbatim}
print 1, a == 6
print 2, a == 7
\end{verbatim}
print out a 1 and a 0 respectively just as expected since the first is true and the second is false. The third print, \verb'print 3,a == 6 and b == 7', is a little different. The operator {\tt and} means if both the statement before and the statement after are true then the whole expression is true otherwise the whole expression is false. The next line, \verb'print 4,a == 7 and b == 7', shows how if part of an {\tt and} expression is false, the whole thing is false. The behavior of {\tt and} can be summarized as follows:
\begin{tabular}{l | l}
expression & result \\
\hline
true and true & true \\
true and false & false \\
false and true & false \\
false and false & false \\
\end{tabular}
Notice that if the first expression is false Python does not check the second expression since it knows the whole expression is false.
The next line, \verb'print 5,not a == 7 and b == 7', uses the {\tt not} operator. {\tt not} just gives the opposite of the expression (The expression could be rewritten as {\tt print 5,a != 7 and b == 7}). Heres the table:
\begin{tabular}{l | l}
expression & result \\
\hline
not true & false \\
not false & true \\
\end{tabular}
The two following lines, \verb'print 6,a == 7 or b == 7' and \verb'print 7,a == 7 or b == 6', use the {\tt or} operator. The {\tt or} operator returns true if the first expression is true, or if the second expression is true or both are true. If neither are true it returns false. Here's the table:
\begin{tabular}{l | l}
expression & result \\
\hline
true or true & true \\
true or false & true \\
false or true & true \\
false or false & false \\
\end{tabular}
Notice that if the first expression is true Python doesn't check the second expression since it knows the whole expression is true. This works since {\tt or} is true if at least one half of the expression is true. The first part is true so the second part could be either false or true, but the whole expression is still true.
The next two lines, \verb'print 8,not (a == 7 and b == 6)' and \verb'print 9,not a == 7 and b == 6', show that parentheses can be used to group expressions and force one part to be evaluated first. Notice that the parentheses changed the expression from false to true. This occurred since the parentheses forced the {\tt not} to apply to the whole expression instead of just the {\tt a == 7} portion.
Here is an example of using a boolean expression:
\begin{verbatim}
list = ["Life","The Universe","Everything","Jack","Jill","Life","Jill"]
#make a copy of the list. See the More on Lists chapter to explain what
#[:] means.
copy = list[:]
#sort the copy
copy.sort()
prev = copy[0]
del copy[0]
count = 0
#go through the list searching for a match
while 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 found
if count < len(copy):
print "First Match: ",prev
\end{verbatim}
And here is the output:
\begin{verbatim}
First Match: Jill
\end{verbatim}
This program works by continuing to check for match {\tt while count < len(copy and copy[count]}. When either {\tt count} is greater than the last index of {\tt copy} or a match has been found the {\tt and} is no longer true so the loop exits. The {\tt if} simply checks to make sure that the {\tt while} exited because a match was found.
The other `trick' of {\tt and} is used in this example. If you look at the table for {\tt and} notice that the third entry is ``false and won't check''. If {\tt count >= len(copy)} (in other words {\tt count < len(copy)} is false) then copy[count] is never looked at. This is because Python knows that if the first is false then they both can't be true. This is known as a short circuit and is useful if the second half of the {\tt and} will cause an error if something is wrong. I used the first expression ({\tt count < len(copy)}) to check and see if {\tt count} was a valid index for {\tt copy}. (If you don't believe me remove the matches `Jill' and `Life', check that it still works and then reverse the order of {\tt count < len(copy) and copy[count] != prev} to {\tt copy[count] != prev and count < len(copy)}.)
Boolean expressions can be used when you need to check two or more different things at once.
\section{Examples}
password1.py
\begin{verbatim}
## This programs asks a user for a name and a password.
# It then checks them to make sure 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."
\end{verbatim}
Sample runs
\begin{verbatim}
What is your name? Josh
What is the password? Friday
Welcome Josh
What is your name? Bill
What is the password? Money
I don't know you.
\end{verbatim}
\section{Exercises}
Write a program that has a user guess your name, but they only get 3 chances
to do so until the program quits.
\chapter{Dictionaries}
This chapter is about dictionaries. Dictionaries have keys and values. The keys are used to find the values. Here is an example of a dictionary in use:
\begin{verbatim}
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 = 0
print_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()
\end{verbatim}
And here is my output:
\begin{verbatim}
1. Print Phone Numbers
2. Add a Phone Number
3. Remove a Phone Number
4. Lookup a Phone Number
5. Quit
Type in a number (1-5):2
Add Name and Number
Name:Joe
Number:545-4464
Type in a number (1-5):2
Add Name and Number
Name:Jill
Number:979-4654
Type in a number (1-5):2
Add Name and Number
Name:Fred
Number:132-9874
Type in a number (1-5):1
Telephone Numbers:
Name: Jill Number: 979-4654
Name: Joe Number: 545-4464
Name: Fred Number: 132-9874
Type in a number (1-5):4
Lookup Number
Name:Joe
The number is 545-4464
Type in a number (1-5):3
Remove Name and Number
Name:Fred
Type in a number (1-5):1
Telephone Numbers:
Name: Jill Number: 979-4654
Name: Joe Number: 545-4464
Type in a number (1-5):5
\end{verbatim}
This program is similar to the name list earlier in the chapter on lists. Heres how the program works. First the function \verb'print_menu' is defined. \verb'print_menu' just prints a menu that is later used twice in the program. Next comes the funny looking line {\verb'numbers = {}'}. All that line does is tell Python that {\tt numbers} is a dictionary. The next few lines just make the menu work. The lines:
\begin{verbatim}
for x in numbers.keys():
print "Name: ",x," \tNumber: ",numbers[x]
\end{verbatim}
go through the dictionary and print all the information. The function {\tt numbers.keys()} returns a list that is then used by the {\tt for} loop. The list returned by {\tt keys} is not in any particular order so if you want it in alphabetic order it must be sorted. Similar to lists the statement {\tt numbers[x]} is used to access a specific member of the dictionary. Of course in this case {\tt x} is a string. Next the line {\tt numbers[name] = phone} adds a name and phone number to the dictionary. If {\tt name} had already been in the dictionary {\tt phone} would replace whatever was there before. Next the lines:
\begin{verbatim}
if numbers.has_key(name):
del numbers[name]
\end{verbatim}
see if a name is in the dictionary and remove it if it is. The function \verb'numbers.has_key(name)' returns true if {\tt name} is in {\tt numbers} but other wise returns false. The line {\tt del numbers[name]} removes the key {\tt name} and the value associated with that key. The lines:
\begin{verbatim}
if numbers.has_key(name):
print "The number is",numbers[name]
\end{verbatim}
check to see if the dictionary has a certain key and if it does prints out the number associated with it. Lastly if the menu choice is invalid it reprints the menu for your viewing pleasure.
\label{firstgrades}
A recap: Dictionaries have keys and values. Keys can be strings or
numbers. Keys point to values. Values can be any type of variable
(including lists or even dictionaries (those dictionaries or lists of
course can contain dictionaries or lists themselves (scary right? :)
)). Here is an example of using a list in a dictionary:
\begin{verbatim}
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"
\end{verbatim}
\begin{verbatim}
def print_all_grades():
print '\t',
for i in range(len(assignments)):
print assignments[i],'\t',
print
keys = students.keys()
keys.sort()
for x in keys:
print x,'\t',
grades = students[x]
print_grades(grades)
\end{verbatim}
\begin{verbatim}
def print_grades(grades):
for i in range(len(grades)):
print grades[i],'\t\t',
print
\end{verbatim}
\begin{verbatim}
print_menu()
menu_choice = 0
while menu_choice != 6:
print
menu_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',
print
print_grades(grades)
which = 1234
while which != -1:
which = input("Change which Grade:")
which = which-1
if 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()
\end{verbatim}
and here is a sample output:
\begin{verbatim}
1. Add student
2. Remove student
3. Print grades
4. Record grade
5. Print Menu
6. Exit
Menu Choice (1-6):3
hw ch 1 hw ch 2 quiz hw ch 3 test
#Max 25 25 50 25 100
\end{verbatim}
\begin{verbatim}
Menu Choice (1-6):6
1. Add student
2. Remove student
3. Print grades
4. Record grade
5. Print Menu
6. Exit
Menu Choice (1-6):1
Student to add:Bill
\end{verbatim}
\begin{verbatim}
Menu Choice (1-6):4
Record Grade
Student:Bill
Type in the number of the grade to record
Type a 0 (zero) to exit
1 hw ch 1 2 hw ch 2 3 quiz 4 hw ch 3 5 test
0 0 0 0 0
Change which Grade:1
Grade:25
Change which Grade:2
Grade:24
Change which Grade:3
Grade:45
Change which Grade:4
Grade:23
Change which Grade:5
Grade:95
Change which Grade:0
\end{verbatim}
\begin{verbatim}
Menu Choice (1-6):3
hw ch 1 hw ch 2 quiz hw ch 3 test
#Max 25 25 50 25 100
Bill 25 24 45 23 95
Menu Choice (1-6):6
\end{verbatim}
Heres how the program works. Basically the variable {\tt students} is
a dictionary with the keys being the name of the students and the
values being their grades. The first two lines just create two lists.
The next line \verb"students = {'#Max':max_points}" creates a new
dictionary with the key {\verb'#Max'} and the value is set to be {\tt
[25,25,50,25,100]} (since thats what \verb'max_points' was when the
assignment is made) (I use the key \verb'#Max' since \verb'#' is sorted
ahead of any alphabetic characters). Next \verb'print_menu' is
defined. Next the \verb'print_all_grades' function is defined in the
lines:
\begin{verbatim}
def print_all_grades():
print '\t',
for i in range(len(assignments)):
print assignments[i],'\t',
print
keys = students.keys()
keys.sort()
for x in keys:
print x,'\t',
grades = students[x]
print_grades(grades)
\end{verbatim}
Notice how first the keys are gotten out of the {\tt students} dictionary with the {\tt keys} function in the line {\tt keys = students.keys() }. {\tt keys} is a list so all the functions for lists can be used on it. Next the keys are sorted in the line {\tt keys.sort()} since it is a list. {\tt for} is used to go through all the keys. The grades are stored as a list inside the dictionary so the assignment {\tt grades = students[x]} gives {\tt grades} the list that is stored at the key {\tt x}. The function \verb'print_grades' just prints a list and is defined a few lines later.
The later lines of the program implement the various options of the menu. The line \verb'students[name] = [0]*len(max_points)' adds a student to the key of their name. The notation \verb'[0]*len(max_points)' just creates a array of 0's that is the same length as the \verb'max_points' list.
The remove student entry just deletes a student similar to the telephone book example. The record grades choice is a little more complex. The grades are retrieved in the line {\tt grades = students[name]} gets a reference to the grades of the student {\tt name}. A grade is then recorded in the line {\tt grades[which] = grade}. You may notice that {\tt grades} is never put back into the students dictionary (as in no {\tt students[name] = grades}). The reason for the missing statement is that {\tt grades} is actually another name for {\tt students[name]} and so changing {\tt grades} changes {\tt student[name]}.
Dictionaries provide an easy way to link keys to values. This can be used to easily keep track of data that is attached to various keys.
\chapter{Using Modules}
Here's this chapter's typing exercise (name it cal.py)\footnote{import actually looks for a file named calendar.py and reads it in. If the file is named calendar.py and it sees a 'import calendar' it tries to read in itself which works poorly at best.}:
\begin{verbatim}
import calendar
year = input("Type in the year number:")
calendar.prcal(year)
\end{verbatim}
And here is part of the output I got:
\begin{verbatim}
Type in the year number:2001
2001
January February March
Mo 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 4
8 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 18
22 23 24 25 26 27 28 19 20 21 22 23 24 25 19 20 21 22 23 24 25
29 30 31 26 27 28 26 27 28 29 30 31
\end{verbatim}
(I skipped some of the output, but I think you get the idea.) So what does the program do? The first line {\tt import calendar} uses a new command {\tt import}. The command {\tt import} loads a module (in this case the {\tt calendar} module). To see the commands available in the standard modules either look in the library reference for python (if you downloaded it) or go to {\tt http://www.python.org/doc/current/lib/lib.html}. The calendar module is described in 5.9. If you look at the documentation lists a function called {\tt prcal} that prints a calendar for a year. The line {\tt calendar.prcal(year)} uses the function. In summary to use a module {\tt import} it and then use module\_name.function for functions in the module. Another way to write the program is:
\begin{verbatim}
from calendar import prcal
year = input("Type in the year number:")
prcal(year)
\end{verbatim}
This version imports a specific function from a module. Here is another program that uses the Python Library (name it something like clock.py) (press Ctrl and the 'c' key at the same time to kill the program):
\begin{verbatim}
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
\end{verbatim}
With some output being:
\begin{verbatim}
The time is: Sun Aug 20 13:40:04 2000
The time is: Sun Aug 20 13:40:05 2000
The time is: Sun Aug 20 13:40:06 2000
The time is: Sun Aug 20 13:40:07 2000
Traceback (innermost last):
File "clock.py", line 5, in ?
the_time = ctime(time())
KeyboardInterrupt
\end{verbatim}
The output is infinite of course so I canceled it (or the output at least continues until Ctrl+C is pressed). The program just does a infinite loop and each time checks to see if the time has changed and prints it if it has. Notice how multiple names after the import statement are used in the line {\tt from time import time, ctime}.
The Python Library contains many useful functions. These functions give your programs more abilities and many of them can simplify programming in Python.
\section{Exercises}
Rewrite the high_low.py program from section \ref{firsthighlow} to use the last two
digits of time at that moment to be the 'random' number.
\chapter{More on Lists}
We have already seen lists and how they can be used. Now that you have some more background I will go into more detail about lists. First we will look at more ways to get at the elements in a list and then we will talk about copying them.
Here are some examples of using indexing to access a single element of an list:
\begin{verbatim}
>>> list = ['zero','one','two','three','four','five']
>>> list[0]
'zero'
>>> list[4]
'four'
>>> list[5]
'five'
\end{verbatim}
All those examples should look familiar to you. If you want the first item in the list just look at index 0. The second item is index 1 and so on through the list. However what if you want the last item in the list? One way could be to use the \verb'len' function like \verb'list[len(list)-1]'. This way works since the \verb'len' function always returns the last index plus one. The second from the last would then be \verb'list[len(list)-2]'. There is an easier way to do this. In Python the last item is always index -1. The second to the last is index -2 and so on. Here are some more examples:
\begin{verbatim}
>>> list[len(list)-1]
'five'
>>> list[len(list)-2]
'four'
>>> list[-1]
'five'
>>> list[-2]
'four'
>>> list[-6]
'zero'
\end{verbatim}
Thus any item in the list can be indexed in two ways: from the front and from the back.
Another useful way to get into parts of lists is using slices. Here is another example to give you an idea what they can be used for:
\begin{verbatim}
>>> list = [0,'Fred',2,'S.P.A.M.','Stocking',42,"Jack","Jill"]
>>> 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']
\end{verbatim}
Slices are used to return part of a list. The slice operator is in the form \verb'list[first_index:following_index]'. The slice goes from the \verb'first_index' to the index before the \verb'following_index'. You can use both types of indexing:
\begin{verbatim}
>>> list[-4:-2]
['Stocking', 42]
>>> list[-4]
'Stocking'
>>> list[-4:6]
['Stocking', 42]
\end{verbatim}
Another trick with slices is the unspecified index. If the first index is not specified the beginning of the list is assumed. If the following index is not specified the whole rest of the list is assumed. Here are some examples:
\begin{verbatim}
>>> list[:2]
[0, 'Fred']
>>> list[-2:]
['Jack', 'Jill']
>>> list[:3]
[0, 'Fred', 2]
>>> list[:-5]
[0, 'Fred', 2]
\end{verbatim}
Here is a program example (copy and paste in the poem definition if you want):
\begin{verbatim}
poem = ["<B>","Jack","and","Jill","</B>","went","up","the","hill","to","<B>",\
"fetch","a","pail","of","</B>","water.","Jack","fell","<B>","down","and",\
"broke","</B>","his","crown","and","<B>","Jill","came","</B>","tumbling",\
"after"]
def get_bolds(list):
true = 1
false = 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 = 0
for index in range(len(list)):
##Handle a starting of bold text
if list[index] == "<B>":
if is_bold:
print "Error: Extra Bold"
##print "Not Bold:",list[start_block:index]
is_bold = true
start_block = index+1
##Handle end of bold text
##Remember that the last number in a slice is the index
## after the last index used.
if list[index] == "</B>":
if not is_bold:
print "Error: Extra Close Bold"
print "Bold [",start_block,":",index,"] ",\
list[start_block:index]
is_bold = false
start_block = index+1
get_bolds(poem)
\end{verbatim}
with the output being:
\begin{verbatim}
Bold [ 1 : 4 ] ['Jack', 'and', 'Jill']
Bold [ 11 : 15 ] ['fetch', 'a', 'pail', 'of']
Bold [ 20 : 23 ] ['down', 'and', 'broke']
Bold [ 28 : 30 ] ['Jill', 'came']
\end{verbatim}
The \verb'get_bold' function takes in a list that is broken into words
and token's. The tokens that it looks for are \verb'<B>' which starts
the bold text and \verb'<\B>' which ends bold text. The function
\verb'get_bold' goes through and searches for the start and end
tokens.
The next feature of lists is copying them. If you try something simple like:
\begin{verbatim}
>>> a = [1,2,3]
>>> b = a
>>> print b
[1, 2, 3]
>>> b[1] = 10
>>> print b
[1, 10, 3]
>>> print a
[1, 10, 3]
\end{verbatim}
This probably looks surprising since a modification to {\tt b}
resulted in {\tt a} being changed as well. What happened is that the
statement \verb'b = a' makes {\tt b} a {\em reference} to {\tt a}.
This means that {\tt b} can be thought of as another name for {\tt a}.
Hence any modification to {\tt b} changes {\tt a} as well. However
some assignments don't create two names for one list:
\begin{verbatim}
>>> 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]
\end{verbatim}
In this case {\tt b} is not a reference to {\tt a} since the
expression \verb'a*2' creates a new list. Then the statement
\verb'b = a*2' gives {\tt b} a reference to \verb'a*2' rather than a
reference to {\tt a}. All assignment operations create a reference.
When you pass a list as a argument to a function you create a
reference as well. Most of the time you don't have to worry about
creating references rather than copies. However when you need to make
modifications to one list without changing another name of the list
you have to make sure that you have actually created a copy.
There are several ways to make a copy of a list. The simplest that
works most of the time is the slice operator since it always makes a
new list even if it is a slice of a whole list:
\begin{verbatim}
>>> a = [1,2,3]
>>> b = a[:]
>>> b[1] = 10
>>> print a
[1, 2, 3]
>>> print b
[1, 10, 3]
\end{verbatim}
Taking the slice {\tt [:]} creates a new copy of the list. However it
only copies the outer list. Any sublist inside is still a references
to the sublist in the original list. Therefore, when the list
contains lists the inner lists have to be copied as well. You could
do that manually but Python already contains a module to do it. You
use the {\tt deepcopy} function of the {\tt copy} module:
\begin{verbatim}
>>> 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]]
\end{verbatim}
First of all notice that {\tt a} is an array of arrays. Then notice
that when \verb'b[0][1] = 10' is run both {\tt a} and {\tt b} are
changed, but {\tt c} is not. This happens because the inner arrays
are still references when the slice operator is used. However with
{\tt deepcopy} {\tt c} was fully copied.
So, should I worry about references every time I use a function or
\verb'='? The good news is that you only have to worry about
references when using dictionaries and lists. Numbers and strings
create references when assigned but every operation on numbers and
strings that modifies them creates a new copy so you can never modify
them unexpectedly. You do have to think about references when you are
modifying a list or a dictionary.
By now you are probably wondering why are references used at all? The
basic reason is speed. It is much faster to make a reference to a
thousand element list than to copy all the elements. The other reason
is that it allows you to have a function to modify the inputed list
or dictionary. Just remember about references if you ever have some
weird problem with data being changed when it shouldn't be.
%% On Sun, Sep 09, 2001 at 02:46:06PM +0100, Hamish Lawson wrote:
%% Hello Josh
%%
%% I think it's great that you have undertaken to write a non-programmer's
%% tutorial on Python. However may I suggest that a different approach to
%% the discussion of variables and references may make things easier for
%% both you and the reader, and lead to less potential confusion for the
%% novice when they explore Python further?
%%
%% Programming introductions that use a language like C or Pascal as the
%% medium often discuss variables in terms of boxes that store data. But
%% for a language like Python, I think this approach ends up making the
%% whole subject of variables and references more complicated than it need
%% be and means that the reader has a lot to unlearn later.
%%
%% Saying that "a = []" stores an empty list in 'a' and that "b = a" makes
%% 'b' a reference to 'a' makes it appear that assignment is
%% context-dependent when it isn't really. Things get even trickier when
%% you have statements like "b = f()". Instead a more coherent approach
%% might be to say that assignment to a variable stores a reference to
%% some object. The difference between "a = []" and "b = a" then lies in
%% whether it is a newly created object that you are storing a reference
%% to (as produced by '[]') or an existing object (as produced by 'a'),
%% *not* in whether or not a reference gets stored in the variable - it
%% always does. I believe this approach leads to much less confusion
%% overall and less need for special explanations.
%%
%% Fredrik Lundh has a good explanation of objects and references in
%% Python at http://www.effbot.org/guides/python-objects.htm.
%%
%% I hope you have found this useful.
\chapter{Revenge of the Strings}
%%things to talk about: chr ord float int len repr s+b s[i] s[i:j] s*n find rfind replace strip
%%Start with indexing, user chr and ord to show how to do manual int<->string
%%Repeate the <B> with slices and do actual html
%%Do some more phrasing
%%Okay here is todays typing exercise:
%%\begin{verbatim}
%%def 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_str
%% in_int = in_int / 10
%% out_str = chr(ord('0')+in_int % 10) + out_str
%% return prefix + out_str
%%
%%def to_int(in_str):
%% "Converts a string to an integer"
%% out_num = 0
%% if in_str[0] == "-":
%% multiplier = -1
%% in_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")
%%\end{verbatim}
%%The output is:
%%\begin{verbatim}
%%2
%%23445
%%-23445
%%14234
%%12345
%%-3512
%%\end{verbatim}
%%
%%So how does it work? The first detail to notice is that it defines two different functions, one that converts a string to a number and one that converts a number to a string. Notice that this function does string manipulation similar to how lists can be manipulated. For example the line \verb'if in_str[0] == "-"' uses indexing to look at the first letter in the string. Another thing that strings can do that lists can is using slices. The line \verb'in_str = in_str[1:]' uses slices to get all but the first character of in_str (or drops the first letter). However you cannot use slices or indexing to assign to a letter or location in a string.
%%
%%Two new things to introduced are the functions \verb'ord' and \verb'chr'. The
%%\verb'ord' function takes a character (a string of length one) and returns the ASCII value of the character. The function \verb'chr' is its inverse and takes a ASCII value and returns a character. The expression \verb"ord(in_str[x]) - ord('0')" uses the \verb'ord' function to find the value of a string. This works since '0' through '9' have ASCII values that are all in a row. The ASCII value of '0' is 48 and the ASCII value of '9' is 57 so when we subtract 57-48 we get 9 and this works similarly with other numbers. The expression \verb"chr(ord('0')+in_int % 10)" works in a similar manor but in reverse.
And now presenting a cool trick that can be done with strings:
\begin{verbatim}
def shout(string):
for character in string:
print "Gimme a "+character
print "'"+character+"'"
shout("Lose")
def middle(string):
print "The middle character is:",string[len(string)/2]
middle("abcdefg")
middle("The Python Programming Language")
middle("Atlanta")
\end{verbatim}
And the output is:
\begin{verbatim}
Gimme a L
'L'
Gimme a o
'o'
Gimme a s
's'
Gimme a e
'e'
The middle character is: d
The middle character is: r
The middle character is: a
\end{verbatim}
What these programs demonstrate is that strings are similar to lists in several ways. The {\tt shout} procedure shows that {\tt for} loops can be used with strings just as they can be used with lists. The middle procedure shows that that strings can also use the {\tt len} function and array indexes and slices. Most list features work on strings as well.
The next feature demonstrates some string specific features:
\begin{verbatim}
def to_upper(string):
## Converts a string to upper case
upper_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 + character
return upper_case
print to_upper("This is Text")
\end{verbatim}
with the output being:
\begin{verbatim}
THIS IS TEXT
\end{verbatim}
This works because the computer represents the characters of a string as numbers from 0 to 255. Python has a function called {\tt ord} (short for ordinal) that returns a character as a number. There is also a corresponding function called {\tt chr} that converts a number into a character. With this in mind the program should start to be clear. The first detail is the line: \verb$if 'a' <= character <= 'z':$ which checks to see if a letter is lower case. If it is, then the next lines are used. First it is converted into a location so that a=0,b=1,c=2 and so on with the line: \verb$location = ord(character) - ord('a')$. Next the new value is found with \verb$new_ascii = location + ord('A')$. This value is converted back to a character that is now upper case.
Now for some interactive typing exercise:
\begin{verbatim}
>>> #Integer to String
...
>>> 2
2
>>> repr(2)
'2'
>>> -123
-123
>>> repr(-123)
'-123'
>>> #String to Integer
...
>>> "23"
'23'
>>> int("23")
23
>>> "23"*2
'2323'
>>> int("23")*2
46
>>> #Float to String
...
>>> 1.23
1.23
>>> repr(1.23)
'1.23'
>>> #Float to Integer
...
>>> 1.23
1.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
\end{verbatim}
If you haven't guessed already the function \verb'repr' can convert a integer to a string and the function \verb'int' can convert a string to an integer. The function {\tt float} can convert a string to a float. The \verb'repr' function returns a printable representation of something. Here are some examples of this:
\begin{verbatim}
>>> repr(1)
'1'
>>> repr(234.14)
'234.14'
>>> repr([4,42,10])
'[4, 42, 10]'
\end{verbatim}
The \verb'int' function tries to convert a string (or a float) into a integer. There is also a similar function called \verb'float' that will convert a integer or a string into a float. Another function that Python has is the \verb'eval' function. The \verb'eval' function takes a string and returns data of the type that python thinks it found. For example:
\begin{verbatim}
>>> 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'>
\end{verbatim}
If you use the \verb'eval' function you should check that it returns the type that you expect.
One useful string function is the \verb'split' function. Here's the example:
\begin{verbatim}
>>> 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']
\end{verbatim}
Notice how \verb'split' converts a string into a list of strings. The string is split by spaces by default or by the optional second argument (in this case a comma).
%%TODO add more on strings
\section{Examples}
\begin{verbatim}
#This program requires an excellent understanding of decimal numbers
def 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_str
in_int = in_int / 10
out_str = chr(ord('0')+in_int % 10) + out_str
return prefix + out_str
def to_int(in_str):
"Converts a string to an integer"
out_num = 0
if in_str[0] == "-":
multiplier = -1
in_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")
\end{verbatim}
The output is:
\begin{verbatim}
2
23445
-23445
14234
12345
-3512
\end{verbatim}
\chapter{File IO}
Here is a simple example of file IO:
\begin{verbatim}
#Write a file
out_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 file
in_file = open("test.txt","r")
text = in_file.read()
in_file.close()
print text,
\end{verbatim}
The output and the contents of the file test.txt are:
\begin{verbatim}
This Text is going to out file
Look at it and see
\end{verbatim}
Notice that it wrote a file called test.txt in the directory that you ran the program from. The \verb'\n' in the string tells Python to put a {\bf n}ewline where it is.
A overview of file IO is:
\begin{enumerate}
\item Get a file object with the \verb'open' function.
\item Read or write to the file object (depending on how it was opened)
\item Close it
\end{enumerate}
The first step is to get a file object. The way to do this is to use the \verb'open' function. The format is \verb'file_object = open(filename,mode)' where \verb'file_object' is the variable to put the file object, \verb'filename' is a string with the filename, and \verb'mode' is either \verb'"r"' to {\bf r}ead a file or \verb'"w"' to {\bf w}rite a file. Next the file object's functions can be called. The two most common functions are \verb'read' and \verb'write'. The \verb'write' function adds a string to the end of the file. The \verb'read' function reads the next thing in the file and returns it as a string. If no argument is given it will return the whole file (as done in the example).
Now here is a new version of the phone numbers program that we made earlier:
\begin{verbatim}
import string
true = 1
false = 0
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 true:
in_line = in_file.readline()
if in_line == "":
break
in_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
\end{verbatim}
\begin{verbatim}
phone_list = {}
menu_choice = 0
print_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"
\end{verbatim}
Notice that it now includes saving and loading files. Here is some output of my running it twice:
\begin{verbatim}
> python tele2.py
1. Print Phone Numbers
2. Add a Phone Number
3. Remove a Phone Number
4. Lookup a Phone Number
5. Load numbers
6. Save numbers
7. Quit
Type in a number (1-7):2
Add Name and Number
Name:Jill
Number:1234
Type in a number (1-7):2
Add Name and Number
Name:Fred
Number:4321
Type in a number (1-7):1
Telephone Numbers:
Name: Jill Number: 1234
Name: Fred Number: 4321
Type in a number (1-7):6
Filename to save:numbers.txt
Type in a number (1-7):7
Goodbye
\end{verbatim}
\begin{verbatim}
> python tele2.py
1. Print Phone Numbers
2. Add a Phone Number
3. Remove a Phone Number
4. Lookup a Phone Number
5. Load numbers
6. Save numbers
7. Quit
Type in a number (1-7):5
Filename to load:numbers.txt
Type in a number (1-7):1
Telephone Numbers:
Name: Jill Number: 1234
Name: Fred Number: 4321
Type in a number (1-7):7
Goodbye
\end{verbatim}
The new portions of this program are:
\begin{verbatim}
def load_numbers(numbers,filename):
in_file = open(filename,"r")
while 1:
in_line = in_file.readline()
if len(in_line) == 0:
break
in_line = in_line[:-1]
[name,number] = string.split(in_line,",")
numbers[name] = number
in_file.close()
\end{verbatim}
\begin{verbatim}
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()
\end{verbatim}
First we will look at the save portion of the program. First it creates a file object with the command \verb'open(filename,"w")'. Next it goes through and creates a line for each of the phone numbers with the command \verb'out_file.write(x+","+numbers[x]+"\n")'. This writes out a line that contains the name, a comma, the number and follows it by a newline.
The loading portion is a little more complicated. It starts by getting a file object. Then it uses a \verb'while 1:' loop to keep looping until a \verb'break' statement is encountered. Next it gets a line with the line \verb'in_line = in_file.readline()'. The \verb'readline' function will return an empty string (len(string) == 0) when the end of the file is reached. The \verb'if' statement checks for this and \verb'break's out of the \verb'while' loop when that happens. Of course if the \verb'readline' function did not return the newline at the end of the line there would be no way to tell if an empty string was an empty line or the end of the file so the newline is left in what \verb'readline' returns. Hence we have to get rid of the newline. The line \verb'in_line = in_line[:-1]' does this for us by dropping the last character. Next the line \verb'[name,number] = string.split(in_line,",")' splits the line at the comma into a name and a number. This is then added to the \verb'numbers' dictionary.
\section{Exercises}
Now modify the grades program from section \ref{firstgrades} so that is uses file
IO to keep a record of the students.
\chapter{Dealing with the imperfect (or how to handle errors)}
So you now have the perfect program, it runs flawlessly, except for one detail, it will crash on invalid user input. Have no fear, for Python has a special control structure for you. It's called \verb'try' and it tries to do something. Here is an example of a program with a problem:
\begin{verbatim}
print "Type Control C or -1 to exit"
number = 1
while number != -1:
number = int(raw_input("Enter a number: "))
print "You entered: ",number
\end{verbatim}
Notice how when you enter \verb'@#&' it outputs something like:
\begin{verbatim}
Traceback (innermost last):
File "try_less.py", line 4, in ?
number = int(raw_input("Enter a number: "))
ValueError: invalid literal for int(): @#&
\end{verbatim}
As you can see the \verb'int' function is unhappy with the number \verb'@#&' (as well it should be). The last line shows what the problem is; Python found a \verb'ValueError'. How can our program deal with this? What we do is first: put the place where the errors occurs in a \verb'try' block, and second: tell Python how we want \verb'ValueError's handled. The following program does this:
\begin{verbatim}
print "Type Control C or -1 to exit"
number = 1
while number != -1:
try:
number = int(raw_input("Enter a number: "))
print "You entered: ",number
except ValueError:
print "That was not a number."
\end{verbatim}
Now when we run the new program and give it \verb'@#&' it tells us ``That was not a number.'' and continues with what it was doing before.
When your program keeps having some error that you know how to handle, put code in a \verb'try' block, and put the way to handle the error in the \verb'except' block.
\section{Exercises}
Update at least the phone numbers program so it doesn't crash if a
user doesn't enter any data at the menu.
%Road map\\
%boolean expressions\\
%defining functions\\
%more on lists
%modules\\
%dictionaries
%the end\\
%%#########################################################################
%%############## THE END OF THE BOOK #####################
%%#########################################################################
\chapter{The End}
I have run out of interest in adding more to this tutorial. However, I have
put it up on Wikibooks at \url{http://wikibooks.org/wiki/User:Jrincayc/Contents}, where you can edit it and discuss it. For the moment I recommend looking at The Python Tutorial by Guido van Rossum. You should be able to understand a fair amount of it.
This tutorial is very much a work in progress. Thanks to everyone
who has emailed me. If you have comments, I would recomend that
you put them on the Wikibooks version (Note the discussion link on
each page) so that everyone can discuss and think about them.
Happy programming, may it change your life and the world.
TODO=[ 'errors','how to make modules','more on loops','more on strings', 'file io','how to use online help','try','pickle','anything anyone suggests that I think is a good idea']
\chapter{FAQ}
\begin{description}
\item[Can't use programs with input.] If you are using IDLE then try using command line. This problem seems to be fixed in IDLE 0.6 and newer. If you are using an older version of IDLE try upgrading to Python 2.0 or newer.
\item[Is there a printable version?] Yes, see the next question.
\item[Is there a PDF or zipped version?] Yes, go to \url{http://www.honors.montana.edu/\~{}jjc/easytut/} for several different versions.
\item[What is the tutorial written with?] \LaTeX, see the \file{easytut.tex} file.
\item[I can't type in programs of more than one line.] If the
programs that you type in run as soon as you are typing them in, you
need to edit a file instead of typing them in interactive mode. (Hint:
interactive mode is the mode with the \verb'>>>' prompt in front of
it.)
\item[My question is not answered here.] Email me and ask. Please send me source code if at all relevent (even, (or maybe especially) if it doesn't work). Helpful things to include are what you were trying to do, what happened, what you expected to happen, error messages, version of Python, Operating System, and whether or not your cat was stepping on the keyboard. (The cat in my house has a fondness for space bars and control keys.)
\item[I want to read it in a different language.] There are several translations that I know of. One is in korean and is available at:
\url{http://home.hanmir.com/~johnsonj/easytut/easytut.html}. Another is in Spanish and at: \url{http://www.honors.montana.edu/~jjc/easytut/easytut_es/}. Another is in italian and is available at \url{http://www.python.it/doc/tut_begin/index.html}. Another is in Greek and available at \url{http://www.honors.montana.edu/~jjc/easytut/easytut_gr/}. Another is in Russian and is available at \url{http://www.honors.montana.edu/~jjc/easytut/Easytut_Russian/} Several
people have said they are doing a translation in other languages such
as French, but I never heard back from them. If you have done a translation or know of any translations, please either send it to me or send me a link.
\item[How do I make a GUI in Python?] You can use either TKinter at \url{http://www.python.org/topics/tkinter/} or WXPython at \url{http://www.wxpython.org/}
\item[How do I make a game in Python?] The best method is probably to use PYgame at \url{http://pygame.org/}
\item[How do I make an exectable from a Python program?] Short answer: Python is an interepreted language so that is impossible. Long answer is that something similar to an executable can be created by taking the Python interpreter and the file and joining them together and distributing that. For more on that
problem see \url{http://www.python.org/cgi-bin/faqw.py?req=all\#4.28}
\item[I need help with the exercises] Hint, the password program requires two variables, one to keep track of the number of times the password was typed in, and another to keep track of the last password typed in. Also you can download solutions from \url{http://www.honors.montana.edu/\~{}jjc/easytut/}
\item[What and when was the last thing changed?] 2000-Dec-16, added error handling chapter.\\
2000-Dec-22, Removed old install procedure.\\
2001-Jan-16, Fixed bug in program, Added example and data to lists section.\\
2001-Apr-5, Spelling, grammar, added another how to break programs, url fix for PDF version.\\
2001-May-13, Added chapter on debugging. \\
2001-Nov-11, Added exercises, fixed grammar, spelling, and hopefully improved explanations of some things.\\
2001-Nov-19, Added password exercise, revised references section.\\
2002-Feb-23, Moved 3 times password exercise, changed l to list in list examples question. Added a new example to Decisions chapter, added two new exercises.\\
2002-Mar-14, Changed abs to my_abs since python now defines a abs function.\\
2002-May-15, Added a faq about creating an executable. Added a comment from
about the list example. Fixed typos from Axel Kleiboemer.\\
2002-Jun-14, Changed a program to use while true instead of while 1 to
be more clear.\\
2002-Jul-5, Rewrote functions chapter. Modified fib program to hopefully
be clearer.\\
2003-Jan-3, Added average examples to the decisions chapter.\\
2003-Jan-19, Added comment about value of a_var. Fixed mistake in average2.py
program.\\
2003-Sep-5, Changed idle instruction to Run->Run Module.
\end{description}
%%\chapter{Command Line Install}
%%
%%This is here purely for historical reasons.
%%
%%\section{Running Python}
%%This section is somewhat vague since I am trying to explain how to run Python in general and not on a specific machine (though I am writing from a Unix viewpoint). If you have a Microsoft(tm) Windows machine see the next section for details. If you have a Macintosh see http://www.python.org for other documentation.
%%
%%First you should check to see if you can run Python in interactive mode. To do this go to a command prompt and type {\tt python}. If everything is working you should see something like this:
%%\begin{verbatim}
%%Python 1.5.1 (#1, Dec 17 1998, 20:58:15) [GCC 2.7.2.3] on linux2
%%Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
%%>>>
%%\end{verbatim}
%%The {\tt >>>} is Python's way of telling you it is waiting for you to type something in.
%%
%%If you did not get the {\tt >>>} prompt then something is wrong. Check and make sure that you properly installed Python. Check to see that the python executable is in the path.
%%
%%Once you got the Python interpreter running you can play around with it. Here are some things you could try:
%%\begin{verbatim}
%%>>> 1+1
%%2
%%>>> 3*4+5
%%17
%%>>> a=12
%%>>> a
%%12
%%>>> "Hi"
%%'Hi'
%%>>>
%%\end{verbatim}
%%
%%To exit try typing Ctrl+Z or Ctrl+D or if neither of those works type \verb'import sys; sys.exit(0)'. Next, how to run Python programs. First you need create a Python program. To do that you should type in the following in a text editor:\footnote{A text editor is just a program that edits text. If you are in Windows I recommend that you use Notepad or Editpad (http://www.jgsoft.com). If you are in Unix I recommend that you use a text editor that you are comfortable with (if you haven't found one yet use pico, ae, or (x)emacs (emacs has a very nice Python mode BTW)). }
%%\begin{verbatim}
%%print "Hello, World!"
%%\end{verbatim}
%%
%%Now save the file in some convenient location as hello.py. Next go to directory with the file that you save the file in and type {\tt python hello.py}. The screen should look something like this:
%%\begin{verbatim}
%%>python hello.py
%%Hello, World!
%%\end{verbatim}
%%
%%If you get some error message check to make sure you saved the file in the right place.
%%
%%From now on I will mainly give you programs to type in that you should save and then run.
%%%%If you didn't get that and get some error message like bad command or filename or command not found then either Python is not installed or the Python interpreter is not in your path. With Windows you need to have the python.exe file locate in your path. For example, if python.exe is in the directory \verb'C:\PROGRA~1\PYTHON\' then if you add \verb'PATH=C:\PROGRA~1\PYTHON\;%PATH%' to the end of your \verb'AUTOEXEC.BAT' file the next time you reboot your computer python.exe will be found in your path. For Unix find Python with locate and add the directory to the path (or move python).
%%
%%%%There, you now should be able to type in and run a Python program. The later chapters will show you more about how to create a Python program.
%%
%%\section{Windows}
%%First install Python. Then go to a command line which can be done one of two ways: Click {\bf Start>>Programs>>MS-DOS Prompt}, or click {\bf Start>>Run}, then type {\bf command} and hit {\bf Enter}.
%%
%%This will open up a DOS screen with a prompt that probably looks like this:
%%
%%\begin{verbatim}
%%C:\WINDOWS>
%%\end{verbatim}
%%
%%Type {\bf python} and hit {\bf Enter}. If you get {\tt Bad command or file name} then either you forgot to install Python or {\tt python.exe} is not in the {\tt PATH} variable (to see what the {\tt PATH} variable has in it type {\bf PATH}).
%%
%%To fix the problem click {\bf Start>>Find>>Files or Folders} and then look for a file {\bf Named} {\tt python.exe}. If it is found then the problem is the {\tt PATH}, otherwise Python was not properly installed.
%%
%%To fix the {\tt PATH} problem the directory that includes {\tt python.exe} needs to be added to {\tt PATH}. The directory that {\tt python} is in is the folder that {\tt Find} shows to the left of the name. If the whole name is not shown Right click on the python icon and go to {\bf Properties}. The {\tt Properties} dialog will have a line called {\tt Location:} that shows the directory where {\tt python.exe} is at. Next go to the command prompt and type in \verb'PATH="C:\Location of Python\";%PATH%'. For Example:
%%\begin{verbatim}
%%C:\WINDOWS>python
%%Bad command or file name
%%
%%C:\WINDOWS>PATH="C:\Programe Files\Python";%PATH%
%%
%%C:\WINDOWS>python
%%Python 1.5.1 (#0, Apr 13 1998, 20:22:04) [MSC 32 bit (Intel)] on win32
%%Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
%%>>>
%%\end{verbatim}
%%Type Ctrl+Z to get out of interactive mode (i.e. hold down the Ctrl Key and then press down on the Z key at the same time, then release both.).
%%
%%Next type this program in a text editor (such as Notepad):
%%\begin{verbatim}
%%print "Hello, World!"
%%\end{verbatim}
%%and save it in a convenient location such as \verb'C:\python\hello.py'.
%%
%%From here you need to change the path to the Python directory where you saved your first program. The command to do this is (Hit Enter):
%%\begin{verbatim}
%%cd \python
%%\end{verbatim}
%%which should give you a prompt like:
%%\begin{verbatim}
%%C:\Python>
%%\end{verbatim}
%%
%%Now you are ready to run your first program. Just type python hello.py
%%
%%\begin{verbatim}
%%>python hello.py
%%Hello, World!
%%\end{verbatim}
%%
%%From now on in the tutorial I will assume that you know how to create and run programs.
%%
%%
%%\section{Longer Windows install}
%%%%\newcommand{\file}[1]{{\tt#1}}
%%%%\newcommand{\url}[1]{{\tt#1}}
%%
%%\subsection{Download Python}
%%
%%Download \file{py152.exe} from \url{http://www.python.org/download/download\_windows.html} The file is located at \url{ftp://ftp.python.org/pub/python/win32/py152.exe} Download this file and save it to your computer.
%%
%%\subsection{Install Python}
%%
%%Run \file{py152.exe} by double clicking on the executable. This will start the Python installation process. Use the defaults for the install. The computer will restart after this is done.
%%
%%%%The Python installation creates a folder \file{Python 1.5}. Go to Start$\to$ Programs$\to$ Python~1.5
%%
%%\subsection{Add Python to Path}
%%
%%The next step is to add the Python executable to the path. The path specifies how DOS finds commands. First you will find where the Python executable was installed. Next create a \file{PATH} command to tell DOS where to find Python. Lastly add the \file{PATH} command to the autoexec.bat so that it will be permanent. The following tells how to do this.
%%
%%This is what you should do to add Python to the path. First get to an MS-DOS Prompt. The way to get to a MS-DOS Prompt is go to Start$\to$Run. When the Run dialog pops up type \type{command} and press Enter (Note: don't type the ``quotation marks'', just type the stuff between them) (Note two: type Enter after everything that I put in this \type{font}). A window titled MS-DOS Prompt should appear.
%%
%%Type \type{cd \textbackslash{}}. The command \type{cd} stands for change directory. When \type{cd} is followed by a \type{\textbackslash{}} it means change to the root directory. The \file{C:\textbackslash{}>} prompt tells you that you are in the root directory. Once in the root directory the next task is to find Python.
%%
%%Type \type{dir /s python.exe} This should give you some output like:
%%\begin{verbatim}
%%
%% Volume in drive C is WIN 95
%% Volume Serial Number is 283F-12D9
%%
%%Directory of C:\Program Files\Python
%%
%%PYTHON EXE 5,120 04-13-99 11:31a python.exe
%% 1 file(s) 5,120 bytes
%%
%%Total files listed:
%% 1 file(s) 5,120 bytes
%% 0 dir(s) 344,498,176 bytes free
%%
%%\end{verbatim}
%%The important part of this is the line:
%%\begin{verbatim}
%%Directory of C:\Program Files\Python
%%\end{verbatim}
%%which shows the directory that \file{python.exe} is located in. This can be used to create a \file{PATH} variable that allows \file{python} to be run from anywhere on the system. The syntax is \type{PATH=\%PATH\%;"directory"} where directory is the directory that \file{python.exe} is in. For this example the command is:
%%\begin{verbatim}
%%PATH=%PATH%;"C:\Program Files\Python"
%%\end{verbatim}
%%
%%Type this in at the DOS Prompt and then you should be able to run Python with the \type{python} command. If you did everything right you should see (version numbers and dates may be different):
%%\begin{verbatim}
%%Python 1.5.2 (#4, Dec 16 1999, 18:55:39) [GCC 2.7.2.3] on Win 95
%%Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
%%>>>
%%\end{verbatim}
%%If you get the \file{$>>>$} prompt you have gotten into Python. Try typing in it \type{print "Hello"}. You should see \file{Hello} printed. Try tying \type{print 1+1}. You should see \file{2} printed. Type \type{Ctrl-Z} (i.e. type z while holding down the Ctrl key) to get out of Python's interactive mode.
%%
%%If there is some problem with the \file{PATH} then you will see something like:
%%\begin{verbatim}
%%C:\>python
%%Bad command or file name
%%\end{verbatim}
%%
%%Right now the change you made is only temporary. To get Python to be in the \file{PATH} every time the computer starts you need to add it to the \file{autoexec.bat} file. The \file{autoexec.bat} file is run every time the computer starts. To do this open the \file{autoexec.bat} in a text editor like \file{notepad}. Type the command \type{notepad c:\textbackslash{}autoexec.bat} on the DOS Prompt. If you don't have a \file{autoexec.bat} notepad will ask you if you want to create one (say yes). Add the line that you used above (i.e. something like: \type{PATH=\%PATH\%;"C:\textbackslash{}Program Files\textbackslash{}Python"}) to the \file{autoexec.bat}. Add the line as close to the bottom as you can, just don't add the line after a line that tells windows to load:
%%\begin{verbatim}
%%PATH=%PATH%;"C:\Program Files\Python"
%%win
%%\end{verbatim}
%%The \file{win} loads Windows so I added the path line above it. If you don't see a \file{win} line add the path line to the end. Save the \file{autoexec.bat} file, reboot your computer and it should be install.
%%
%%When your computer boots again go to the DOS Prompt and try to run \type{python} again to see if the change was successful.
%%
%%\subsection{Running Programs}
%%
%%Now that Python is set up we need to use it to run programs. Go to a DOS Prompt (Start$\to$Run, then type \type{command}). Change to the root directory (\type{cd \textbackslash{} }). Now make a directory with the command \type{mkdir prg} which makes the directory \file{prg}. Switch into that directory with the \type{cd prg} command. Create a file there by typing the \type{notepad hello.py} command. That will open a \file{notepad} window. In Notepad type:
%%\begin{verbatim}
%%print "Hello, World!"
%%\end{verbatim}
%%Save the file and then go back to the DOS Prompt. Now type \type{python hello.py} in at the DOS Prompt. Python should reply with \file{Hello, World!} if everything is working right. If you get the error:
%%\begin{verbatim}
%%Bad command or file name
%%\end{verbatim}
%%check to see if the path is correct. Also check to make sure that you spelled \file{python} correctly. If you get the error:
%%\begin{verbatim}
%%C:\PROGRA~1\PYTHON\PYTHON.EXE: can't open file 'hello.py'
%%\end{verbatim}
%%check to see that you properly saved the \file{hello.py} file and that you are in the correct directory.
%%
%%Once you have that working create another file with the \type{notepad ask.py} command. Put the following text in the file:
%%\begin{verbatim}
%%data = raw_input("Type something here:")
%%print "You typed:",data
%%\end{verbatim}
%%Save and then run with the \type{python ask.py} command. The program should ask you to type in data and after you hit Enter it will tell you what you type. You should get something like this:
%%\begin{verbatim}
%%Type something here:Hi
%%You typed: Hi
%%\end{verbatim}
%%If you got that, congratulations, you now have a working Python environment.
%\chapter{...}
%My appendix.
%The \code{\e appendix} mark-up need not be repeated for additional
%appendices.
%
% The ugly "%begin{latexonly}" pseudo-environments are really just to
% keep LaTeX2HTML quiet during the \renewcommand{} macros; they're
% not really valuable.
%
% If you don't want the Module Index, you can remove all of this up
% until the second \input line.
%
%begin{latexonly}
%\renewcommand{\indexname}{Module Index}
%end{latexonly}
%\input{mod\jobname.ind} % Module Index
%begin{latexonly}
\renewcommand{\indexname}{Index}
%end{latexonly}
\input{\jobname.ind} % Index
\end{document}