Copyright © 2006 David Schmidt

Chapter 1:
Introduction to Python


1.1 Simple Python
1.2 Erroneous instructions: bad grammatical structure
1.3 Scripts: commands you save in a file
1.4 Summary of basic Python commands
    1.4.1 Installing Python


First, read Chapter 1 of Dawson's text. Next, install Python on your computer, or go to the CIS lab in Nichols Hall 16 or 126 or the EECE labs in Seaton 54 or Fiedler 1092 to use Python. See the comments at the end of this chapter about installing and using Python.

We begin our studies with programming linguistics, that is, learning how to read and write in the programing language, Python.

From the previous lecture, we learned that a computer's processor understands instructions to do arithmetic on numbers copied into its data registers. For example, we might write these machine-language instructions (in binary --- 1s and 0s-coding!) to tell it to add together 2 and 3 and display the sum:

  1. copy 00010 into Data Register #1
  2. copy 00011 into Data Register #2
  3. add the numbers in Registers 1 and 2 and copy the sum into Data Register #3
  4. copy the number in Register 3 to the display
These instructions would be placed in a file. Then, we tell the operating system to ``start the program,'' which means the operating system copies the the file into primary storage, where the processor reads the instructions and does them one by one.

Although the first computer programmers wrote programs like this, we need not do so. In this chapter, we will learn an algebra-like programming language, named Python, that will let us state the computation much more simply; the previous program looks like this in the language of Python:

print 2 + 3
The name, python, is actually the name of a computer program that can read your key presses and translate them into machine language for the computer processor. This hides all the details about binary arithmetic and binary-coded machine language and makes it look like we are ``talking'' directly to the processor.


1.1 Simple Python

The Python language lets you ``talk'' to the computer within a command window; there are no icons or graphical buttons in the way to prevent you from ``saying the wrong thing'' (and indeed, we will make mistakes along the way!).

To talk to the computer in Python, you should do this with a command window:

Select the Start button in the lower left corner of your display, then select the All Programs menu, then Accessories and then Command Prompt. A command window will appear. Within the command window, type:
python
(See the section at the end of this chapter for more details.)

The computer is ready to understand you in the language of Python. It will show you this prompt:

>>>
It looks like this in the window:

You can talk now. Say that you want the computer to repeat what you are saying. Do it with the command, print:
>>> print "I like humans"
I like humans
>>> print "I like humans...\nfor lunch!"
I like humans...
for lunch!
Here is what you see:

As you may have guessed, the verb, print, commands the computer to display (``print'') the information that follows. The text to be displayed must be enclosed within double-quote marks ("). Such text is called a string. A string is literally is sequence of key presses that we make on a keyboard. If we wish to include the ``newline'' (``Enter'') keypress into a string, we type \n instead.

We can command that the computer adds the first 5 prime numbers and display the answer:

>>> print  2 + 3 + 5 + 7 + 11
28
Here, the computer first calculated the addition and then displayed the answer.

Type these two commands:

print "The sum of the first 5 primes is:"
print 2 + 3 + 5 + 7 + 11
As you type them one at a time, you will see this in the command window:
>>> print "The sum of the first 5 primes is:"
The sum of the first 5 primes is:
>>> print 2 + 3 + 5 + 7 + 11
28
Here is a second example, that computes a multiplication:
>>> print "2 cubed is", (2 * 2 * 2)
2 cubed is 8
We see here that multiplication is represented by a star (*) and that we can print two items on same line if we separate the items by a comma.

These little examples show that the purpose of the print command is to display knowledge computed by the computer. Here, the computer displayed the knowledge that the sum of the first five primes is 28 and that two cubed is 8. We are using the computer as if it were a terribly expensive, overpowered, arithmetic calculator.

In the previous chapter, about computer hardware, we learned that an electronic computer contains wiring circuits to compute arithmetic knowledge. In the previous examples, the computer is reading your commands, written in Python, and does them one by one. But the computer's CPU understands only binary patterns of 1s-and-0s (on-and-off), so somehow the Python words must be converted into the binary patterns. How does this happen ?

When you started Python, you told the computer to execute a helper program, called the Python interpreter, that displays the >>>. When you type your commands, the Python interpreter program sees them, converts them into binary, and tells the CPU to execute the binary patterns. The answers are converted from binary back into Python and displayed in the command window.

When you are tired of talking in Python, you can type exit.


1.2 Erroneous instructions: bad grammatical structure

Restart the Python interpreter and try these examples:
print "abc" 

print "ab" + "c"

print "abc" + "9"

print "abc" + 9
The first three examples display simple knowledge about strings; the second and third examples show that, in the Python language, you can demand that the computer concatenate (``add'') two strings together, a kind of ``string arithmetic,'' with +. But the last example gives this response:
>>> print "abc" + 9
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: cannot concatenate 'str' and 'int' objects
There is an error --- we have spoken grammatically incorrectly --- and the Python interpreter tells us that it is impossible to complete our command, because the + symbol can do arithmetic with two numbers and it can do arithmetic with two strings, but it cannot do arithmetic on a mixture of a string ('str') and a number ('int').

These examples show that arithmetic expressions (like 2 + 3 + 5 + 7 + 11 and "abc" + "9") have grammatical structure, just like English phrases and sentences possess. To make the point even more strongly, try this ``command'':

2 + 3  print
You will see
>>> 2 + 3 print
  File "", line 1
    2 + 3 print
              ^
SyntaxError: invalid syntax
The command has incorrect grammatical (``syntax'') structure. At the end of the chapter, we will find summary of the proper grammatical structure of the Python command forms seen so far.


1.3 Scripts: commands you save in a file

When you would like to save some Python commands in a file so that you can use them later (this is like writing down a recipe), you must type them into a file. The file is called a program or script.

First, make a folder in your computer where you will save your files of Python commands. You might make this new folder as

C:\MyPython
You can make the new folder in two ways:
  1. Within a file window: press Start and select MyComputer. Within the file window that appears, double-click on the C: icon. Then, click on the Make a new Folder item in the left side of the window, and type the name MyPython under the newly appeared folder.
  2. Within the command window: press Start and select All programs and Accessories and Command Prompt; a command window appears. Type
    cd c:\
    mkdir MyPython
    

Next, use a text editor, like notepad, to type these commands and save them in a file named Primes.py in folder MyPython:


This is a script or program.

You can use Notepad in two ways:

  1. press Start and select All programs and Accessories and Notepad. Type the above program. Then select the File menu and SaveAs. Within the window that appears, locate the folder C:\MyPython, and type the name, Primes.py. Press Save.
  2. Use a command window: Type
    cd c:\MyPython
    notepad Primes.py
    
    This opens the correct folder, starts Notepad, and tells it the name of the file you want to make. After you type the file, as seen above, use the File menu and select Save.

Now, you can tell the computer to execute the script. You can do this in two ways:

  1. Within a File window: generate a File Window and open the C: icon and then MyPython. At this point, you should see the icon for Primes.py. Double-click on it. (Or, right-click and select OPEN.)

  2. Within the command window: Type
    set path=C:\Python22
    
    (Note: This command tells the computer where the Python interpreter lives. The command can be omitted if you permanently set Window XP's PATH variable, as described at the end of this chapter.) Next, type
    cd C:\MyPython
    
    This opens the folder where you saved the program. Finally, type
    python Primes.py
    
    This executes the program.
In either case, you will see:
The sum of the first 5 primes is:
28

press Enter to finish
When you press the Enter button on your keyboard, the program finishes:

Once you have typed and saved your program, Primes.py, in the folder, C:\MyPython, you can also edit it by right-clicking on its icon, selecting OpenWith, and selecting Notepad.

Finally, you can make a ``shortcut icon'' for quick-starting and editing your program: Right-click on the program's icon and select MakeShortcut. Move the icon that appears to your desktop. Now, the program is ready for quick use.


1.4 Summary of basic Python commands

GRAMMAR DESCRIPTION EXAMPLES
print DATA displays the DATA
print "Game Over"
print 3 * 2
raw_input(STRING) displays the STRING and waits for the human (``user'') to type something on the keyboard and press Enter raw_input("Please type something")
# COMMENT (DOCUMENTATION) gives one line of explanation about the program for a human to read # This program computes 2 cubed.
the usual arithmetic expressions using numbers, addition (+), subtraction (-), multiplication (*), division (/), and parentheses computes the answer of the expression
3 + 2 + 1
3 * (2 - 4)
STRING + STRING concatenates two strings into one "abc" + "d"


1.4.1 Installing Python

If your computer uses Windows XP or 2000 or 98 and Python is not already installed on your computer, then you can use the CD enclosed with your textbook to install Python.

First, you should verify that Python is not already installed. To check this, start a new command window and type python. If you see a message stating command not recognized, then Python does not exist on your computer. But if you see the Python prompt, >>>, shown in the example at the beginning of this chapter, then it does. If Python exists on your computer, speak to the instructor, who will advise you whether additional software is needed.

Assuming that Python does not exist on your computer, then use the textbook's CD for installing Python 2.2 or 2.3 or 2.4:

  1. Insert the disk into your computer's disk drive; click on Start, and then MyComputer, and then the disk drive to view the contents of the disk.
  2. If you see a web page with a copy of the book's cover, then you are ready to go. If not, click on (open) the file named start here, and you will see the web page with a copy of the book's cover.
  3. Click on I agree and then Software. Then click on install Python 2.2. This starts an installer program that asks you a couple of simple questions and then installs Python in a new folder, C:\Python22.

At this point, you can start Python within a command window, or you can use a text editor to write a Python program (script), and double-click on the program's icon to start it.

In particular, when you open a new command window, you should first type, set path=C:\Python22, and this makes visible the Python software. It is a bit annoying to type this command every time you open a command window, and there is a clever repair --- you can reset permanently the value of Windows's PATH variable so that Windows knows once and for all that Python is available at C:\Python22. Here is what you must do on Windows XP to reset to Path variable:

  1. press Start
  2. select Control Panel
  3. On the Control Panel window, in the left column, press Switch to classic view (If you don't see this text, go to the next step below.)
  4. Double click on the icon for System
  5. In the System window, click on Advanced
  6. Click on the button Environment Variables
  7. In the new window, scroll until you see the variable, Path; click on it
  8. Press Edit
  9. Carefully use the right arrow button to move to the end of the long sequence of folder names. At the very end, without including any extra blanks, type this:
    ;C:\Python22
    
  10. Press OK twice.
These steps make Python known to Windows XP.

Now, check if you have done the job correctly: Open a new command window, type path, and you will see the text you edited for the Path variable. You should see ;C:\Python22 at the end.

Next, type python. You should see the >>>.