1.1 Your First Program

In this section, our plan is to lead you into the world of Python programming by taking you through the basic steps required to get a simple program running. The Python system (hereafter abbreviated Python) is a collection of applications, not unlike many of the other applications that you are accustomed to using (such as your word processor, email program, and web browser). As with any application, you need to be sure that Python is properly installed on your computer. It comes preloaded on many computers, or you can download it easily. You also need a text editor and a terminal application. Your first task is to follow the instructions for installing such a Python programming environment. Here are system-specific instructions for three popular home operating systems. [ Windows · Mac OS X · Linux ]

Programming in Python

To program in Python, you need to:

Composing a Python Program

A Python program is nothing more than a sequence of characters stored in a file whose name has a .py extension. To create one, you need only define that sequence characters using a text editor.

The program helloworld.py is an example of a complete Python program. We repeat the program in this page to facilitate the following description. The line numbers are shown to make it easy to reference specific lines, but they are not part of the program and should not be in your helloworld.py file.

1  import stdio
3  # Write 'Hello, World' to standard output.
4  stdio.writeln('Hello, World')

The program's sole action is to write a message back to the terminal window. A Python program consists of statements. Typically you place each statement on a distinct line.

Python 2

. The lingua france in this booksite is Python 3, because it is the future of Python programming. However, we have been very careful to ensure that the code in the booksite works with either Python 2 or Python 3. For example, in Python 2, the helloworld.py program could be simply the single line print 'Hello, World', but this is not a valid program in Python 3. To develop code for writing output that works in either version of Python, we use our stdio module. Whenever there is a significant difference between the two languages, we call attention to Python 2 users in a callout box like this one.

Executing a Python Program

Once you compose the program, you can run (or execute) it. To run your program the Python compiler translates your Python program into a language that is more suitable for execution on a computer. Then the Python interpreter directs your computer to follow the instructions expressed in that language. To run your program, type the python command followed by the name of the file containing the Python program in a terminal window.

$ python helloworld.py

If all goes well, you will see the following response:

Hello, World

For the time being, all of your programs will be just like helloworld.py, except with a different sequence of statements. The easiest way to compose such a program is to:


It is easy to blur the distinction among editing, compiling, and interpreting programs. You should keep them separate in your mind when you are learning to program, to better understand the effects of the errors that inevitably arise. You can find several examples of errors in the Q&A at the end of this section.

You can fix or avoid most errors by carefully examining the program as you create it. Some errors, known as compile-time errors, are raised when Python compiles the program, because they prevent the compiler from doing the translation. Python reports a compile-time error as a SyntaxError. Other errors, known as run-time errors, are not raised until Python interprets the program. For example, if you forget the import stdio statement in helloworld.py, then Python will raise a NameError at run time.

Input and Output

Typically, we want to provide input to our programs, that is, data that they can process to produce a result. The simplest way to provide input data is illustrated in useargument.py. Whenever you run that program, it accepts the command-line argument that you type after the program name and writes it back out to the terminal as part of the message.

$ python useargument.py Alice
Hi, Alice. How are you?
$ python useargument.py Bob
Hi, Bob. How are you?

In useargument.py, the statement import sys tells Python that you wish to use the features defined in the sys module. One of those features, named argv, is a list of command-line arguments (which appear after python useargument.py on the command line, delimited by spaces). Section 1.4 describes lists in detail; for now it is sufficient to understand that sys.argv[1] is the first command-line argument that you type after the program name, sys.argv[2] is the second command-line argument that you type after the program name, and so forth.

In addition to stdio.writeln(), useargument.py calls the stdio.write() function. This function is just like stdio.writeln(), but writes just the string (not a newline character).

Getting More Information

We encourage you to visit the official Python website, http://www.python.org, frequently while using this booksite. More specifically:

Programming Style

The final item in that list deserves some elaboration. Concerning programming style...

The overarching goal when composing code is to make it easy to understand. Understandable programs are more likely to be correct, and are more likely to stay correct as they are maintained over time.

Programmers use style guides to make programs easier to understand. As noted above, the official Python style guide is given by the page http://www.python.org/dev/peps/pep-0008/. We recommend that you give the style guide a quick read now, and that your return to it occasionally as you gain more experience with composing Python programs.

Appendix B complements the official Python style guide, providing recommendations that are appropriate for those who are new to computer programming. We recommend that you give Appendix B a guick read now, and return to it occasionally.

Q & A

Q. Why Python?

A. The programs that we are studying are very similar to their counterparts in several other languages, so our choice of language is not crucial. We use Python because it is widely available, embraces a full set of modern abstractions, and has a variety of automatic checks for mistakes in programs, so it is suitable for learning to program. Python is evolving and comes in many versions.

Q. Which version of Python should I use?

A. We recommend Python 3, but we have been very careful to ensure that the code in the book works with either Python 2 or Python 3. All of the code has been tested with Python versions 2.7 and 3.4 (the latest major releases of Python 2 and Python 3 at the time of publication). We use the generic term Python 2 to refer to Python 2.7 and Python 3 to refer to Python 3.4.

Q. Do I really have to type in the programs in the book to try them out? I believe that you ran them and that they produce the indicated output.

A. You should type in and run helloworld.py. Your understanding will be greatly magnified if you also run useargument.py, try it on various inputs, and modify it to test different ideas of your own.

Q. When I run helloworld.py, Python generates the message

ImportError: No module named stdio.

What does that mean?

A. That means that the booksite module stdio is not available to Python.

Q. How can I make the booksite module stdio available to Python?

A. If you followed the step-by-step instructions on the booksite for installing a Python programming environment, the stdio module should already be available to Python.

Q. What are Python's rules regarding whitespace characters such as tabs, spaces, and newlines?

A. In general, Python considers most whitespace in program text to be equivalent, with two important exceptions: string literals and indentation. A string literal is a sequence of characters inside single quotes, such as 'Hello, World'. If you put any number of spaces within the quotes, you get precisely the same number of spaces in the string literal. Indentation is whitespace at a beginning of a line. The number of spaces at the beginning of a line plays an important role in structuring Python programs, as we will see in Section 1.3. For now you should not indent any code.

Q. Why should I use comments?

A. Comments are indispensable because they help other programmers to understand your code and even can help you to understand your own code in retrospect. Whereas constraints of the book format demand that we use comments sparingly in the programs shown in the book, the programs on this booksite are commented to a more realistic degree.

Q. Can I put more than one statement on a line?

A. Yes, by separating statements with semicolons. For example, this single line of code produces the same output as helloworld.py:

import stdio; stdio.writeln('Hello, World')

But many programmers advise against doing this, as a matter of style.

Q. What happens when you omit a parenthesis or misspell one of the words, like stdio or write or writeln?

A. It depends upon precisely what you do. These so-called syntax errors are usually caught by the compiler. For example, if you make a program bad.py that is exactly the same as helloworld.py except that you omit the first left parenthesis, you get the following reasonably helpful message:

% python bad.py
  File "bad.py", line 4
    stdio.write'Hello, World')
SyntaxError: invalid syntax

From this message, you might correctly surmise that you need to insert a left parenthesis. But the compiler may not be able to tell you exactly which mistake you made, so the error message may be hard to understand. For example, if you omit the first right parenthesis instead of the first left parenthesis, you get the following less helpful message, which references the line following the erroneous one:

% python bad.py
  File "bad.py", line 5
SyntaxError: unexpected EOF while parsing

One way to get used to such messages is to intentionally introduce mistakes into a simple program and then see what happens. Whatever the error message says, you should treat the compiler as a friend, because it is just trying to tell you that something is wrong with your program.

Q. When I run useargument.py, I get a strange error message. Please explain.

A. Most likely, you forgot to include a command-line argument:

% python useargument.py
Hi, Traceback (most recent call last):
  File "useargument.py", line 5, in 
IndexError: list index out of range

The Python interpreter is complaining that you ran the program but did not type a command-line argument as promised. You will learn more details about list indices in Section 1.4. Remember this error message: you are likely to see it again. Even experienced programmers forget to type command-line arguments on occasion.

Q. Which Python modules and functions are available for me to use?

A. Many standard modules are bundled with any Python installation. Many others are available as extension modules that you can download and install subsequently. We composed still others (such as the stdio module) specifically for this book and booksite; we'll call them booksite modules. In short, hundreds of Python modules, each (typically) defining multiple functions, are available for you to use. This book introduces only the most fundamental modules and functions, and does so in a deliberately incremental fashion (starting in the next section) to avoid overwhelming you with information.


  1. Compose a program that writes the Hello, World message 10 times.
  2. Solution: See tenhellos1.py.

  3. Describe what happens if you omit the following in helloworld.py:
    1. import
    2. stdio
    3. import stdio
  4. Describe what happens if you misspell (by, say, omitting the second letter) the following in helloworld.py:
    1. import
    2. stdio
    3. write
    4. writeln
  5. Describe what happens if you omit the following in helloworld.py:
    1. the first '
    2. the second '
    3. the stdio.writeln() statement
  6. Describe what happens if you try to execute useargument.py with each of the following command lines:
    1. python useargument.py python
    2. python useargument.py @!&^%
    3. python useargument.py 1234
    4. python useargument Bob
    5. useargument.py Bob
    6. python useargument.py Alice Bob
  7. Modify useargument.py to compose a program that takes three names and writes a proper sentence with the names in the reverse of the order they are given, so that, for example, python usethree.py Alice Bob Carol writes the string 'Hi Carol, Bob, and Alice'.
  8. Solution: See usethree.py.

  9. Compose a program that writes your initials using nine rows of asterisks like the one below.

    **        ***    **********      **             *             **
    **      ***      **        **     **           ***           **
    **    ***        **         **     **         ** **         **
    **  ***          **          **     **       **   **       **
    *****            **          **      **     **     **     **
    **  ***          **          **       **   **       **   **
    **    ***        **         **         ** **         ** **
    **      ***      **        **           ***           ***
    **        ***    **********              *             *

    Solution: See initials.py.