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. 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.
You must install either a Python 3 or a Python 2 programming environment.
Here are instructions for installing a Python 2 programming environment [ Windows · Mac OS X · Linux ]. We recommend that you use the Python 2 programming environment only if you have a compelling reason (external to the requirements of this book and booksite) to do so.
Programming in Python
To program in Python, you need to:
- Compose a program by typing it into a file named, say,
- Run (or execute) it by typing
python myprogram.pyin the terminal window.
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 2 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.
- Line 1 contains an
importstatement. That statement tells Python that you intend to use the features defined in the
stdiomodule, that is, in a file named
stdio.pyfile is one that we designed specifically for this book. It defines functions related to reading input and writing output. Having imported the
stdiomodule, you can later call a function that is defined in that module.
- Line 2 is a blank line. Python ignores blank lines; programmers use them to separate logical blocks of code.
- Line 3 contains a comment, which serves to document the program. In Python a comment begins with the '#' character and extends to the end of the line. Python ignores comments; they are present only for human readers of the program.
- Line 4 is the heart of the program. It is a statement that calls the
stdio.writeln()function to write one line with the given text on it. Note that we call a function in another module by writing the module name, followed by a period, followed by the function name.
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
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:
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:
- Copy helloworld.py into a new file whose name is the program name followed by
- Replace the call of
stdio.writeln()with a different statement or sequence of statements.
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 is the first command-line argument that you type after the program name,
sys.argv 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:
- http://docs.python.org/reference/index.htm provides information on the Python language.
- http://docs.python.org/library/index.html provides information on the Python standard libraries.
- http://www.python.org/dev/peps/pep-0008/ provides information on Python 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.
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
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 stdio.write(sys.argv) 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.
- Compose a program that writes the
Hello, Worldmessage 10 times.
- Describe what happens if you omit the following in helloworld.py:
- Describe what happens if you misspell (by, say, omitting the second letter) the following in helloworld.py:
- Describe what happens if you omit the following in helloworld.py:
- the first
- the second
- Describe what happens if you try to execute useargument.py with each of the following command lines:
python useargument.py python
python useargument.py @!&^%
python useargument.py 1234
python useargument Bob
python useargument.py Alice Bob
- 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 Carolwrites the string
'Hi Carol, Bob, and Alice'.
Compose a program that writes your initials using nine rows of asterisks like the one below.
** *** ********** ** * ** ** *** ** ** ** *** ** ** *** ** ** ** ** ** ** ** *** ** ** ** ** ** ** ***** ** ** ** ** ** ** ** *** ** ** ** ** ** ** ** *** ** ** ** ** ** ** ** *** ** ** *** *** ** *** ********** * *
Solution: See initials.py.
Solution: See tenhellos1.py.
Solution: See usethree.py.