\documentclass{manual}
\usepackage{verbatim}
\usepackage{hyperref}
\title{Non-Programmers Tutorial For Python 2 and 3}
\author{Josh Cogliati}
%\date{May 10, 2016}
\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-2018 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.
At your option you may instead distribute and modify this document
under the Creative Commons Attribution-ShareAlike 2.0 license.
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.
ISBN: 978-1-387-75719-0
%%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 2.6 and 3 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, and PDF. Go to http://jjc.freeshell.org/easytut23/ to see all these forms.
If you have any questions or comments please contact me at jjc at sdf.lonestar.org \ 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 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 also to James
A. Brown, Hamish Lawson, Amos Satterlee, Gerald, Elissa, Quique and
Annie Brewer. Thanks to everyone I have missed.
\ifhtml
Here are a few links that you may find useful:
\begin{rawhtml}
\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:
\verbatiminput{scripts/helloshort.py}
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 \url{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}
If you are on a Unix or macOS computer, you probably already have
Python installed. If you are on a Windows computer you will need to install Python. To install Python download the appropriate file for your computer from
\url{http://www.python.org/download}. You will need Python 2.6 or newer for this tutorial.
\section{Interactive Mode}
From the command line, interactive mode can be gotten to by typing \verb'python' or \verb'python3' depending on the version of Python that you have. Alternatively, you can go into IDLE (also called the Python GUI). You should see a window that has some text like this:
\begin{verbatim}
Python 2.6.6 (r266:84292, Dec 27 2010, 21:57:32)
[GCC 4.4.5 20100902 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
\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:
\verbatiminput{scripts/hellofirst.py}
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'. 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. For those of you who don't want to use IDLE, to
get into interactive mode just type \verb'python' or \verb'python3'
with out any arguments. To run a program create it with a text editor
(Emacs has a good python mode, Notepad++ also has a python mode) and
then run it with \verb'python program_name.py' or
\verb'python3 program_name.py'.
%%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 or flash) 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:
\verbatiminput{scripts/hellofirst.py}
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} (or \type{python3 hello.py} if using Python 3).
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 ( note that there are two
underscores before the future and two after):
\verbatiminput{scripts/jack.py}
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, first it sees the line:
\begin{verbatim}
from __future__ import division, print_function
\end{verbatim}
This line tells Python 2.6 and 2.7 to act more like Python 3. Most of
the later programs in this tutorial will not work in Python 2 without
this line. Feel free to copy this line from program to program
instead of typing it in each time. If your program only needs to run
in Python 3 and up, this line is not needed. If you are doing more
complicated programs, there are other future statements available.
When the computer runs this program, next it 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:
\verbatiminput{scripts/expression.py}
And here is the output when the program is run:
\verbatiminput{scripts/expression.out}
As you can see Python can turn your thousand dollar computer into a 5 dollar calculator.
Python has seven 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'15 / 2 == 7.5' \\
Integer 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 there are two different division rules. If you use \verb'//' then it returns the integer result (\verb'15 // 2 == 7'). If you use \verb'/' then it returns the decimal result (\verb'15 / 2 == 7.5'). The following program show this:
\verbatiminput{scripts/division.py}
With the output:
\verbatiminput{scripts/division.out}
The order of operations is the same as in math:
\begin{enumerate}
\item parentheses \verb'()'
\item exponents \verb'**'
\item multiplication \verb'*', division \verb'\', integer 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:
\verbatiminput{scripts/notpi.py}
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}
Most chapters 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
\verbatiminput{scripts/denmark.py}
Output:
\verbatiminput{scripts/denmark.out}
School.py
\verbatiminput{scripts/school.py}
Output:
\verbatiminput{scripts/school.out}
\section{Exercises}
Write a program that prints your full name and your birthday as separate strings.
Write a program that shows the use of at least 4 of the 7 math functions.
\chapter{Who Goes There?}
\section{Input and Variables}
Now I feel it is time for a really complicated program. Here it is:
\verbatiminput{scripts/whogoesthere.py}
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'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.
Unfortunately, Python 2 and Python 3 have different names for
\verb'input'. The second, third and fourth line of this code will be
explained in more detail later in the tutorial, for now they will just
have be considered magic. In Python 2 the function used for input is
\verb'raw_input' so the following code in program checks for that and
renames it if needed:
\begin{verbatim}
import sys
if sys.version_info.major == 2:
input = raw_input
\end{verbatim}
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:
\verbatiminput{scripts/variables.py}
And here is the output:
\verbatiminput{scripts/variables.out}
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.\footnote{Python allows more types of variables. For example, trick with {\tt input = raw\_input} used functions as a variable type.}
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:
\verbatiminput{scripts/variables2.py}
And of course here is the output:
\verbatiminput{scripts/variables2.out}
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:
\verbatiminput{scripts/floatinput.py}
The output I got was:
\begin{verbatim}
Type in a Number: 12.34
Type in a String: Hello
num = 12.34
num is a
num * 2 = 24.68
str = Hello
str is a
str * 2 = HelloHello
\end{verbatim}
Notice that \verb'num' was gotten with {\tt float(input)} while \verb'str' was gotten with \verb'input'. \verb'input' returns a string and the function {\tt float} converts it to a floating point number.
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
\verbatiminput{scripts/ratetimes.py}
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}
\verbatiminput{scripts/area.py}
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
\verbatiminput{scripts/temperature.py}
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:
\verbatiminput{scripts/while.py}
And here is the extremely exciting output:
\verbatiminput{scripts/while.out}
(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 {\tt a} is zero so it is less than 10. In other words while {\tt a} is less than ten the computer will run the tabbed in statements.
Here is another example of the use of {\tt while}:
\verbatiminput{scripts/sumwhile.py}
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 {\tt a} is zero run the indented statements that are afterwards. (Note: be consistent, always use spaces or tabs to indent, never mix them.)
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
\verbatiminput{scripts/fibonnacci.py}
Output:
\verbatiminput{scripts/fibonnacci.out}
Password.py
\verbatiminput{scripts/password.py}
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:
\verbatiminput{scripts/if.py}
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 = float(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 a 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 \\
\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 a example:
\verbatiminput{scripts/elif.py}
and the output:
\verbatiminput{scripts/elif.out}
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}
\verbatiminput{scripts/highlow.py}
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
\verbatiminput{scripts/even.py}
Sample runs.
\begin{verbatim}
Tell me a number: 3
3.0 is odd.
Tell me a number: 2
2.0 is even.
Tell me a number: 3.14159
3.14159 is very strange.
\end{verbatim}
average1.py
\verbatiminput{scripts/average1.py}
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
\verbatiminput{scripts/average2.py}
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. Some people find it useful, others don't.
\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:
\verbatiminput{scripts/badperimeter.py}
\question What is the first line Python runs?
\answer The first line is alway run first. For this program, it is:\\
\verb'from __future__ import division, print_function'
\question What does that line do?
\answer Well, it is sorta magic, but it tells Python 2 to act more like Python 3.
\question What is the next line that runs?
\answer In this case it is: \verb'height = float(input("Height: "))'
\question What does that line do?
\answer Prints {\tt Height: }, waits for the user to type a line in, and then converts it to a number, 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 = float(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:
\verbatiminput{scripts/fourdots.py}
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 special line \verb'from __future__ import division, print_function'
\question What does it do?
\answer Tells Python 2 to act like Python 3
\question What is the next line to run?
\answer The next 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(".", end=" ")'
\question What does that line do?
\answer Prints one dot and since the function includes \verb'end=" "' 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(".", end=" ")'
\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(".", end=" ")'
\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(".", end=" ")'
\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 a example of what you could do but shouldn't (so don't type it in):
\verbatiminput{scripts/nofunction.py}
with the output being:
\verbatiminput{scripts/nofunction.out}
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:
\verbatiminput{scripts/myabs.py}
with the output being:
\verbatiminput{scripts/myabs.out}
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:
\verbatiminput{scripts/manyfunctions.py}
with output being:
\verbatiminput{scripts/manyfunctions.out}
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.
\verbatiminput{scripts/varfunc.py}
The output is:
\verbatiminput{scripts/varfunc.out}
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 {\tt 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}
%TODO Move this section to a new chapter, Advanced Functions.
Now we will do a walk through for the following program:
\verbatiminput{scripts/mult.py}
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. Some people find this section helpful, others find it
confusing. If it gets confusing, you can skip it.
\question What is the first thing the program does?
\answer After the magic lines, the first thing done is the function {\tt 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}
Congratulations, you stepped through a complicated function.
\section{Examples}
factorial.py
\verbatiminput{scripts/factorial.py}
Output:
\verbatiminput{scripts/factorial.out}
temperature2.py
\verbatiminput{scripts/temperature2.py}
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
\verbatiminput{scripts/area2.py}
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.0 Height = 3.0 so Area = 12.0
\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 a example of a list being used:
\verbatiminput{scripts/simplelist.py}
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:
\verbatiminput{scripts/lotsoflists.py}
The output is:
\verbatiminput{scripts/lotsoflists.out}
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} function 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 a 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. Note also that the numbers were put in
a new list, and that was sorted, instead of trying to sort a mixed
list. Sorting numbers and strings does not really make sense.
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:
\verbatiminput{scripts/menulist.py}
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
\end{verbatim}
\begin{verbatim}
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 a element of the list.
The next section
\begin{verbatim}
old_name = input("What name would you like to change: ")
if old_name in list:
item_number = list.index(old_name)
new_name = 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
\verbatiminput{scripts/pytest.py}
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:
\verbatiminput{scripts/forloop.py}
and the ever-present output:
\verbatiminput{scripts/forloop.out}
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:
\verbatiminput{scripts/shortforloop.py}
Here are some examples to show what happens with the {\tt range} command (converted into a list with the {\tt list} function):
\begin{verbatim}
>>> list(range(1, 10))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(-32, -20))
[-32, -31, -30, -29, -28, -27, -26, -25, -24, -23, -22, -21]
>>> list(range(5, 21))
[5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
>>> list(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:
\verbatiminput{scripts/demofor.py}
The output is:
\verbatiminput{scripts/demofor.out}
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 use the \verb'end=""' (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:
\verbatiminput{scripts/forsum.py}
with the output simply being:
\verbatiminput{scripts/forsum.out}
Or you could write a program to find out if there are any duplicates in a list like this program does:
\verbatiminput{scripts/listdup.py}
and for good measure:
\verbatiminput{scripts/listdup.out}
Okay, so how does it work? Here is a special debugging version to help you understand (you don't need to type this in):
\verbatiminput{scripts/listdupdebug.py}
with the output being:
\verbatiminput{scripts/listdupdebug.out}
The reason I put so many {\tt print} functions 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 prints 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:
\verbatiminput{scripts/fibfor.py}
with the surprising output:
\verbatiminput{scripts/fibfor.out}
Everything that can be done with {\tt for} loops can also be done with {\tt while} loops but {\tt for} loops give a 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):
\verbatiminput{scripts/lotsbool.py}
With the output being:
\verbatiminput{scripts/lotsbool.out}
What is going on? The program consists of a bunch of funny looking {\tt print} functions. Each {\tt print} function prints a number and a expression. The number is to help keep track of which statement I am dealing with. Notice how each expression ends up being either True or False.
%%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 True and a False respectively just as expected since the first is true since is 6 and the second is false since a is not 7. 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 {\tt and} true & true \\
true {\tt and} false & false \\
false {\tt and} true* & false \\
false {\tt 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
{\tt not} true & false \\
{\tt 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 {\tt or} true* & true \\
true {\tt or} false* & true \\
false {\tt or} true & true \\
false {\tt 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:
\verbatiminput{scripts/booldup.py}
And here is the output:
\verbatiminput{scripts/booldup.out}
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 the * on the third and fourth entries because these are not checked. 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
\verbatiminput{scripts/password1.py}
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:
\verbatiminput{scripts/phone.py}
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: Fred Number: 132-9874
Name: Jill Number: 979-4654
Name: Joe Number: 545-4464
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 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 sorted(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 as is done with the {\tt sorted} function. 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 name in numbers:
del numbers[name]
\end{verbatim}
see if a name is in the dictionary and remove it if it is. The function \verb'name in numbers' 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 name in numbers:
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:
\verbatiminput{scripts/firstgrades.py}
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', end=' ')
for i in range(len(assignments)):
print(assignments[i], '\t', end=' ')
print()
keys = list(students.keys())
keys.sort()
for x in keys:
print(x, '\t', end=' ')
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 = list(students.keys()) }. {\tt keys} is converted into 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 a 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.}:
\verbatiminput{scripts/cal.py}
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} (well, we have seen it, but never explained it before). 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 https://docs.python.org/3/library/index.html}. The calendar module is described in 8.2. If you look at the documentation it 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:
\verbatiminput{scripts/cal2.py}
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 __future__ import division, print_function
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.
Also, finally, we can explain the code fragment we have been using for programs with input:
\begin{verbatim}
import sys
if sys.version_info.major == 2:
input = raw_input
\end{verbatim}
The module {\tt sys} includes a variable for the which version of Python is running, so we import it. Then we use an {\tt if} statement to switch \verb'raw_input' to \verb'input' if we are still in Python 2.
\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:
\verbatiminput{scripts/bold.py}
with the output being:
\verbatiminput{scripts/bold.out}
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'' 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 the same list that {\tt a} is a reference to.
This means that {\tt b} and {\tt a} are different names for the same list.
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 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:
\verbatiminput{scripts/shout.py}
And the output is:
\verbatiminput{scripts/shout.out}
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 program demonstrates some string specific features:
\verbatiminput{scripts/upper.py}
with the output being:
\verbatiminput{scripts/upper.out}
This works because the computer represents the characters of a string as numbers from 0 to 255 (or more if they are Unicode). 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 than 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'
\end{verbatim}
\begin{verbatim}
>>> #String to Integer
...
>>> "23"
'23'
>>> int("23")
23
>>> "23"*2
'2323'
>>> int("23")*2
46
\end{verbatim}
\begin{verbatim}
>>> #Float to String
...
>>> 1.23
1.23
>>> repr(1.23)
'1.23'
\end{verbatim}
\begin{verbatim}
>>> #Float to Integer
...
>>> 1.23
1.23
>>> int(1.23)
1
>>> int(-1.23)
-1
\end{verbatim}
\begin{verbatim}
>>> #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')
>>> v, type(v)
(123, )
>>> v=eval('645.123')
>>> v, type(v)
(645.123, )
>>> v=eval('[1, 2, 3]')
>>> v, type(v)
([1, 2, 3], )
\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 that is part of any string. Here's the example:
\begin{verbatim}
>>> "This is a bunch of words".split()
['This', 'is', 'a', 'bunch', 'of', 'words']
>>> "First batch, second batch, third, fourth".split(",")
['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}
\verbatiminput{scripts/inttostring.py}
The output is:
\verbatiminput{scripts/inttostring.out}
\chapter{File IO}
Here is a simple example of file IO:
\verbatiminput{scripts/simpleio.py}
The output and the contents of the file test.txt are:
\verbatiminput{scripts/simpleio.out}
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 if you open it with a {\tt "r"} or {\tt "w"})
\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 objects 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:
\verbatiminput{scripts/phoneio.py}
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 True:
in_line = in_file.readline()
if len(in_line) == 0:
break
in_line = in_line[:-1]
[name, number] = in_line.split(",")
numbers[name] = number
in_file.close()
\end{verbatim}
\begin{verbatim}
def save_numbers(numbers, filename):
out_file = open(filename, "w")
for x in numbers:
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 True:' 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 a 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:
\verbatiminput{scripts/notry.py}
Notice how when you enter \verb'@#&' it outputs something like:
\begin{verbatim}
Traceback (most recent call last):
File "notry.py", line 8, in
number = int(input("Enter a number: "))
ValueError: invalid literal for int() with base 10: '@#&'
\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:
\verbatiminput{scripts/try.py}
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}
Hopefully, you should be able to program in Python now. There are
some versions of this tutorial on Wikibooks:
\url{https://en.wikibooks.org/wiki/Non-Programmer's_Tutorial_for_Python_2}
and
\url{https://en.wikibooks.org/wiki/Non-Programmer's_Tutorial_for_Python_3}
which are based on this tutorial. You probably can also now
understand the The Python Tutorial by Guido van Rossum at
\url{https://docs.python.org/2/tutorial/index.html} and
\url{https://docs.python.org/3/tutorial/index.html}
If you need to write more complicated programs that work in both
Python 2 and Python 3, the package six might be helpful:
\url{https://pythonhosted.org/six/}
This tutorial has been written on and off since 1999. Thanks to
everyone who has emailed me. If you have comments, feel free to add
them to the talk pages on the wikibooks version or email me.
Happy programming, may it change your life and the world.
\chapter{FAQ}
\begin{description}
\item[Is there an updated version?] Maybe, take a look at the webpage: \url{http://jjc.freeshell.org/easytut23/} and the wikibooks versions:\newline \url{https://en.wikibooks.org/wiki/Non-Programmer's_Tutorial_for_Python_3} \newline \url{https://en.wikibooks.org/wiki/Non-Programmer's_Tutorial_for_Python_2.6}
\item[Is there a printable version?] Yes, see the next question.
\item[Is there a PDF or zipped version?] Yes, go to \url{http://jjc.freeshell.org/easytut23/} for several different versions.
\item[What is the tutorial written with?] \LaTeX, see the \file{easytut23.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 of the Python 2 version that I know of, but none of the Python 2/3 version yet. 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://jjc.freeshell.org/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://jjc.freeshell.org/easytut/easytut_gr/}. Another is in Russian and is available at \url{http://jjc.freeshell.org/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 Windows, one solution to do this is \url{http://www.py2exe.org/} On Unix (Such as Linux or macOS) you can just start the program with \verb'#!/usr/bin/env python3' and make the file executable {\tt chmod +x file.py}
\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://jjc.freeshell.org/easytut23/}
\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}