The Python Interpreter and IDLE

Your Python folder

First, you need to set up a location to store the example programs from this tutorial, as well as your work in this course. If you are on a Mac or Windows computer, follow one of the three choices below to find an appropriate place to download the example code archive examples.zip, and then follow the later instructions to unzip the archive.

Your Own Computer
If you are at your own computer, you can put the folder for your Python programs most anywhere you like.
Your Flash Drive or “The Cloud”

If you do not have your own computer, or you want to have your materials easily travel back and forth between the lab and home, you will need a flash drive. Plug your flash drive into the computer USB port. Please Note: Flash drives are easy for me to forget and leave in the computer.

Cloud storage, like Dropbox, is an excellent tool for storing your these examples, and your class documents.

Temporary
If you (temporarily) do not have a flash drive and you are at a U of R lab computer: You should be able to temporarily store any programs on those computer. You will need to save your work somehow before you log off of the computer. You may want to email individual files to yourself, or rezip the examples folder and send just the one archive file to yourself each time until you remember a flash drive!

We’ll call this new folder your Python folder. A good example would be something like C:\Users\<username>\Documents\csc161, where <username> would be whatever is used on your computer for your user.

Downloading the Examples

To get started with this tutorial, we now need to download some example Python code to run. In your web browser, download the ZIP file of Python examples by right clicking on this link: examples.zip, and selecting “Save As” or the equivalent. Then navigate to save the archive to your Python folder you created in the previous step. Note that the examples, like this version of the tutorial, are for Python 3.0 and later. There were major changes to Python in version 3.0, making it incompatible with Python 2.x, so in this course we use Python 3, not Python 2.7

Once you have the archive, you need to extract the files.

Windows
Navigate to your Python program folder in Windows. Right click on examples.zip, select “Extract All”. This will create the folder examples. End up with a new window showing the contents of the examples folder. This will be your Python folder in later discussion.
Mac
Navigate to your Python program folder in the Finder. Double click on the ZIP file and the expanded examples folder appears.

Warning

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.

Warning

Try to make sure that all the directories leading down to your Python examples directory do not include any spaces in them. In particular, that means you should not place your folder under “My Documents”. Spaces in filenames or directory names can be tricky to deal with if you are not aware of them.

Running A Sample Program

This section assumes Python, version at least 3.1, is already on your computer. Apple Mac comes with Python 2.7, so you will need to download Python 3. Windows does not come with Python at all. To install the latest version of Python, please visit the official Python website.

Before getting to the individual details of Python, you will run a simple text-based sample program. Find madlib.py in your Python folder, set up in Your Python folder.

Options for running the program:

  • If you have trouble with the following options, opening the program in IDLE is discussed in Starting IDLE.

  • In Windows, you can display your folder contents, and double click on madlib.py to start the program.

  • On a Mac, you can Ctrl-click on madlib.py in the Finder, select “Open With”, and choose the “Python Launcher” for your Python 3 version. When you are done with the program, close the terminal window.

  • In Linux (and the Mac) you may be able to open a terminal window, change into your Python examples directory, and enter the command

    python3 madlib.py
    

    If neither of these work, get help.

You can also start IDLE from a Windows command window. You will want the current directory to be where your programs are. You can enter the full path to Python, for instance:

C:\python34\python madlib.py

or if python is in your system’s path, you can skip the part before “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.

A Sample Program, Explained

If you want to get right to the detailed explanations of writing your own Python, you can skip to the next section Starting IDLE. 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 brief explanations. Do not worry if you not totally understand the explanations! Try to get the gist now and the details later. The numbers on the right are not part of the program file. They are added for reference in the comments below:

#! /usr/bin/env python3                                  0
'''                                                      1
String Substitution for a Mad Lib                        2
Adapted from code by Kirby Urner                         3
'''                                                      4
                                                         5
storyFormat = '''                                        6
Once upon a time, deep in an ancient jungle,             7
there lived a {animal}.  This {animal}                   8
liked to eat {food}, but the jungle had                  9
very little {food} to offer.  One day, an               10
explorer found the {animal} and discovered              11
it liked {food}.  The explorer took the                 12
{animal} back to {city}, where it could                 13
eat as much {food} as it wanted.  However,              14
the {animal} became homesick, so the                    15
explorer brought it back to the jungle,                 16
leaving a large supply of {food}.                       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
    story = storyFormat.format(**userPicks)             27
    print(story)                                        28
                                                        29
def addPick(cue, dictionary):                           30
    '''Prompt for a user response using the cue string, 31
    and place the cue-response pair in the dictionary.  32
    '''                                                 33
    prompt = 'Enter an example for ' + cue + ': '       34
    response = input(prompt)                            35
    dictionary[cue] = response                          36
                                                        37
tellStory()                                             38
input('Press Enter to end the program.')                39

Line By Line Explanation

#! /usr/bin/env python3                                  0

This is not technically a part of the program. It is there to tell the operating system what version of Python to choose, since the older Python 2 is incompatible with the newer Python 3. We will mostly run programs from inside the IDLE programming environment, where this line is not needed. To run just by clicking on the program in an operating system window, however, the line is important if your computer also has Python 2.

'''                                                      1 String
Substitution for a Mad Lib                               2
Adapted from code by Kirby Urner                         3
'''                                                      4

1-4: There is multi-line text enclosed in triple quotes. Quoted text is called a string. A string at the very beginning of a program like this is documentation for the file.

5,21,29,37: Blank lines are included for human readability to separate logical parts. The computer ignores the blank lines.

storyFormat = '''                                        6
Once upon a time, deep in an ancient jungle,             7
there lived a {animal}.  This {animal}                   8
liked to eat {food}, but the jungle had                  9
very little {food} to offer.  One day, an               10
explorer found the {animal} and discovered              11
it liked {food}.  The explorer took the                 12
{animal} back to {city}, where it could                 13
eat as much {food} as it wanted.  However,              14
the {animal} became homesick, so the                    15
explorer brought it back to the jungle,                 16
leaving a large supply of {food}.                       17
                                                        18
The End                                                 19
'''                                                     20

6: 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, storyFormat.

7-20: These lines contain the body of the string and the ending triple quotes. This storyFormat string contains some special symbols making it a format string, unlike the string in lines 1-4. The storyFormat string will be used later to provide a format into which substitutions are made. The parts of the string enclosed in braces 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 braces: {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 {…} is currently.

def tellStory():                                        22
    userPicks = dict()                                  23
    addPick('animal', userPicks)                        24
    addPick('food', userPicks)                          25
    addPick('city', userPicks)                          26
    story = storyFormat.format(**userPicks)             27
    print(story)                                        28

22: def is short for definition. This line is the heading of a definition, which makes the name tellStory becomes defined as a short way to refer to the sequence of statements that start indented on line 23, and continue through line 28.

23: 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().

24-26: 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.

27: Assign the name story to a string formed by substituting into storyFormat using definitions from the dictionary userPicks, to give the user’s customized story.

28: This is where all the work becomes visible: Print the story string to the screen.

def addPick(cue, dictionary):                           30
    '''Prompt for a user response using the cue string, 31
    and place the cue-response pair in the dictionary.  32
    '''                                                 33
    prompt = 'Enter an example for ' + cue + ': '       34
    response = input(prompt)                            35
    dictionary[cue] = response                          36

30: 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 34-36. The name 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.

31-33: A documentation comment for the addPick definition.

34: The plus sign here is used to concatenate parts of the string assigned to the name prompt. The current value of cue is placed into the string.

35: The right-hand-side of this equal sign causes an interaction with the user, to input text from the keyboard: 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. This string is assigned to the name response.

36: 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 response typed by the user.

tellStory()                                             38
input('Press Enter to end the program.')                39

38: 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.

39: 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.

Starting IDLE

The program that translates Python instructions and then executes them is the Python interpreter, also known as the Python shell.

This interpreter is embedded in a number of larger programs that make it particularly easy to develop Python programs. One such programming environment is IDLE, and it is a part of the standard distribution of Python.

Read the section that follows for your operating system:

Windows
IDLE is likely found in your Start Menu, directly or through searching.
Mac
You can use Spotlight, searching for “IDLE”, or find it in the /Applications/Python 3.4/ directory, or run the python3 command in the Terminal application.
Linux
The approach depends on the installation. In Ubuntu, you should find IDLE in the Programming section of the Applications menu. You are better starting IDLE from a terminal, with the current directory being your Python folder. You may need a special name set up to distinguish idle for versions 2 and 3, for instance idle3 for version 3.X.

When you start Python, it tells you what version you are running. That way you can always check if you need to update to a newer version, or if you are running the correct version to begin with.

Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 23 2015, 02:52:03)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

IDLE As An Interpreter and A Text Editor

The Interpreter Window

IDLE has two main parts you may choose to display, each with its own window. By default, IDLE will start up showing a Python shell window. This is the interactive Python interpreter. This is where you can enter and execute Python code:

Idle Shell Window

Look at the Python shell. In the shell the last line should look like

>>>

The >>> is the prompt, telling you IDLE is waiting for you to type something. Continuing on the same line enter

6+3

Be sure to end with the Enter key. After the Shell responds, you should see something like

>>> 6+3
9
>>>

The shell evaluates the line you entered, and prints the result. You see Python does arithmetic. At the end you see a further prompt >>> where you can enter your next line… The result line, showing 9, that is produced by the computer, does not start with >>>.

The Edit Window

The Edit window is basically a text editor. If you want to create permanent Python programs that you can run repeadtedly, you can open an editor window and type up code, and save it to a file (ending in .py).

Idle Edit Window

Continue on to The IDLE Editor and Execution to learn more about IDLE’s text editing features.