You have probably used computers to do all sorts of useful and interesting things. In each application, the computer responds in different ways to your input, from the keyboard, mouse or a file. Still the underlying operations are determined by the design of the program you are given. In this set of tutorials you will learn to write your own computer programs, so you can give the computer instructions to react in the way you want.
First let us place Python programming in the context of the computer hardware. At the lowest level in the computer there are instructions built into the hardware. These are very simple, low-level instructions, peculiar to the hardware of your particular type of computer. The instructions are designed to be simple for the hardware to execute, not for humans to follow. The earliest programming was done with such instructions. If was difficult and error-prone. A major advance was the development of higher-level languages and translators for them. Higher-level languages allow computer programmers to write instructions in a format that is easier for humans to understand. For example
z = x+y
is an instruction in many high-level languages that means something like:
No computer understands the high-level instruction directly; it is not in machine language. A special program must first translate instructions like this into machine language. This one high-level instruction might be translated into a sequence of three machine language instructions corresponding to the three step description above:
0000010010000001
0000000010000010
0000010110000011
Obviously high-level languages were a great advance in clarity!
If you follow a broad introduction to computing, you will learn more about the layers that connect low-level digital computer circuits to high-level languages.
There are many high-level languages. The language you will be learning is Python. Python is one of the easiest languages to learn and use, while at the same time being very powerful: It is used by many of the most highly productive professional programmers. A few of the places that use Python extensively are Google, the New York Stock Exchange, Industrial Light and Magic, .... Also Python is a free language! If you have your own computer, you can download it from the Internet....
If you are not sure whether your computer already has Python, continue to Section 1.2.2, and give it a try. If it works, you are all set.
If you do need a copy of Python, go to the Downloads page linked to http://www.python.org. Be careful to choose the version for your operating system and hardware.
You just need to execute the installer, and interact enough to agree to all the default choices. Python works in Windows as well as on Apples and in the free operating system Linux. The latest version is 2.5.
Double-click on the installer. Find and run the MAcPython.mpkg that is inside. Follwow the defaults for installation.
Python is generally installed, though Idle is not always installed. Look for something like 'idle-python' (the name in the Ubuntu distribution).
Although Python is a high-level language, it is not English or some other natural human language. The Python translator does not understand “add the numbers two and three”. Python is a formal language with its own specific rules and formats, which these tutorials will introduce gradually, at a pace intended for a beginner. These tutorials are also appropriate for beginners because they gradually introduce fundamental logical programming skills. Learning these skills will allow you to much more easily program in other languages besides Python. Some of the skills you will learn are breaking down problems into manageable parts and building up creative solutions, and making sure the solutions are clear for humans and also work correctly on the computer.
Guiding Principals for the Hands-on Python Tutorials:
Although this approach is an effective way to introduce material, it is not so good for reference. Referencing is addressed in several ways:
Some people learn better visually and verbally from the very beginning. Some parts of the tutorial will also have links to corresponding flash video segments. Many people will find reading faster and more effective, but the video segments may be particularly useful where a computer interface can be not only explained but actually demonstrated. The links to such segments will be labeled. They will need a broadband link or a CD (not yet generated).
In the Firefox browser, the incremental find is excellent, and particularly useful with the single web page version of the tutorials. (It only fails to search footnotes.) It is particularly easy to jump through different sections in a form like 1.2.4.
Flash Video: Downloading the Tutorials and Examples http://cs.luc.edu/anh/python/hands-on/video/downloadTutorial (useful if you want to see how files are unzipped in Windows rather than read)
First you need to set up a location to store your work and the example programs from this tutorial. If you are on a Windows computer, follow just one of the three choices below to find an appropriate place to download the example archive examples.zip, and then follow the later instructions to unzip the archive.
In Windows, after you have chosen a location for the archive, examples.zip, download it by right clicking on http://cs.luc.edu/anh/python/hands-on/examples.zip and selecting Save As or the equivalent on your browser and then navigate to save the archive to the chosen location on your computer.
Once you have the archive, open a file browser window for that directory, right click on examples.zip, select Extract All. This will create the folder examples. End up with a file browser window showing the contents of the examples folder. This will be your Python folder in later discussion.
Caution 1: On Windows, files in a zip archive can be viewed while they are still in the zip archive. Modifying and adding files is not so transparent. Be sure that you unzip the archive and work from the regular directory that holds the resulting unzipped files.
Caution 2: Make sure that all the directories leading down to your Python examples directory do not include any spaces in them. This will be important in Chapter 4 for the local webserver. In particular, that means you should not place your folder under “My Documents”. A directory like C:\hands-on or C:\python would be fine.
Flash Video: Running a Python Program in Windows http://cs.luc.edu/anh/python/hands-on/video/runningWindowsProgram (useful if you want to see how a Python program can be run in Windows rather than reading)
This section assumes Python is already on your computer. Windows does not come with Python. (To load Python see Section 1.1.2) On a Mac or Linux computer enough of Python comes installed to be able to run the sample program.
Before getting to the individual details of Python, you will run a simple text-based sample program. Find madlib.py in your Python folder (Section 1.2.1).
Options for running the program:
python madlib.py
The latter approach only works in a Windows command window if your operating system execution path is set up to find Python.
In whatever manner you start the program, run it, responding to the prompts on the screen. Be sure to press the enter key at the end of each response requested from you.
Try the program a second time and make different responses.
If you want to get right to the detailed explanations of writing your own Python, you can skip to the next section. If you would like an overview of a working program, even if all the explanations do not make total sense yet, read on. Here is the text of the madlib.py program, followed by line-by-line explanations. The numbers on the right are not part of the program file. They are added for reference in the comments below.
""" 1
String Substitution for a Mad Lib 2
Adapted from code by Kirby Urner 3
""" 4
5
story = """ 6
Once upon a time, deep in an ancient jungle, 7
there lived a %(animal)s. This %(animal)s 8
liked to eat %(food)s, but the jungle had 9
very little %(food)s to offer. One day, an 10
explorer found the %(animal)s and discovered 11
it liked %(food)s. The explorer took the 12
%(animal)s back to %(city)s, where it could 13
eat as much %(food)s as it wanted. However, 14
the %(animal)s became homesick, so the 15
explorer brought it back to the jungle, 16
leaving a large supply of %(food)s. 17
18
The End 19
""" 20
21
def tellStory(): 22
userPicks = dict() 23
addPick('animal', userPicks) 24
addPick('food', userPicks) 25
addPick('city', userPicks) 26
print story % userPicks 27
28
def addPick(cue, dictionary): 29
prompt = "Enter a specific example for %s: " % cue 30
dictionary[cue] = raw_input(prompt) 31
32
tellStory() 33
raw_input("Press Enter to end the program.") 34
Line By Line Explanation
""" 1
String Substitution for a Mad Lib 2
Adapted from code by Kirby Urner 3
""" 4
There is multi-line text enclosed in triple quotes. Quoted text is called a string. A string at the very beginning of a file like this is documentation for the file.
Blank lines are included for human readability to separate logical parts. The computer ignores the blank lines.
story = """ 6
Once upon a time, deep in an ancient jungle, 7
there lived a %(animal)s. This %(animal)s 8
liked to eat %(food)s, but the jungle had 9
very little %(food)s to offer. One day, an 10
explorer found the %(animal)s and discovered 11
it liked %(food)s. The explorer took the 12
%(animal)s back to %(city)s, where it could 13
eat as much %(food)s as it wanted. However, 14
the %(animal)s became homesick, so the 15
explorer brought it back to the jungle, 16
leaving a large supply of %(food)s. 17
18
The End 19
""" 20
The equal sign tells the computer that this is an assignment statement. The computer will now associate the value of the expression between the triple quotes, a multi-line string, with the name on the left, story.
These lines contain the body of the string and the ending triple quotes. This story string is different from the documentation string of lines 1-4. It has a special form, called a format string. It will be used later to provide a format into which substitutions are made. The parts of the string starting with % and ending with s are places a substitute string will be inserted later. The substituted string will come from a custom dictionary that will contain the user's definitions of these words. The words in the parentheses: (animal), (food), (city), indicate that "animal", "food", and "city" are words in a dictionary. This custom dictionary will be created in the program and contain the user's definitions of these words. These user's definitions will be substituted later in the format string where each %(...)s is currently.
def tellStory(): 22
userPicks = dict() 23
addPick('animal', userPicks) 24
addPick('food', userPicks) 25
addPick('city', userPicks) 26
print story % userPicks 27
def is short for def inition. This line is the heading of a def inition, which makes the name tellStory becomes def ined as a short way to refer to the sequence of statements that start indented on line 23, and continue through line 27.
The equal sign tells the computer that this is another assignment statement. The computer will now associate the name userPicks with a new empty dictionary created by the Python code dict().
addPick is the name for a sequence of instructions defined on lines 29-31 for adding another definition to a dictionary, based on the user's input. The result of these three lines is to add definitions for each of the three words 'animal', 'food', and 'city' to the dictionary called userPicks.
This is where all the work becomes visible: Print the story format string with substitutions from the dictionary userPicks, to give the user's customized story. The '%' here is an operator on the string story that essentially means 'with substitutions from'.
def addPick(cue, dictionary): 29
prompt = "Enter a specific example for %s: " % cue 30
dictionary[cue] = raw_input(prompt) 31
This line is the heading of a definition, which gives the name addPick as a short way to refer to the sequence of statements indented on line 30 and line 31. addPick is followed by two words in parenthesis, cue and dictionary. These two words are associated with an actual cue word and dictionary given when this definition is invoked in lines 24-26.
On the right side of the equal sign is an expression involving a format string, much simpler than story. The resulting string just has the current value of cue substituted for the %s. This resulting string is then given the name prompt.
The right-hand-side of this equal sign causes an interaction with the user. The prompt string is printed to the computer screen, and the computer waits for the user to enter a line of text. That line of text then becomes a string inside the program. The left-hand-side of the equal sign is a reference to the definition of the cue word in the dictionary. The whole line ends up making the definition of the current cue word become the string typed by the user.
tellStory() 33
raw_input("Press Enter to end the program.") 34
The definition of tellStory above does not make the computer do anything besides remember what the instruction tellStory means. It is only in this line, with the name, tellStory, followed by parentheses, that the whole sequence of remembered instructions are actually carried out.
This line is only here to accommodate running the program in Windows by double clicking on its file icon. Without this line, the story would be displayed and then the program would end, and Windows would make it immediately disappear from the screen! This line forces the program to continue being displayed until there is another response from the user, and meanwhile the user may look at the output from tellStory.
Flash Video: Starting Idle http://cs.luc.edu/anh/python/hands-on/video/startingIdle (useful if you want to see how to navigate and identify parts of Idle rather than reading)
The program that translates Python instructions and then executes them is the Python interpreter.
This interpreter is embedded in