Internet & World Wide Web How to Program, 3/e
This tutorial presents an introduction to Python—the popular, cross-platform, object-oriented programming language. We show how to create and run a simple Python program and how to work interactively with the Python interpreter.
[Note: This tutorial is an excerpt (Section 35.1) of Chapter 35, Python, from our textbook Internet & World Wide Web How to Program, 3/e
. This tutorial may refer to other chapters or sections of the book that are not included here. Permission Information: Deitel, Harvey M. and Paul J., INTERNET & WORLD WIDE WEB HOW TO PROGRAM, 3/E, ©2004, pp.1242-1246. Electronically reproduced by permission of Pearson Education, Inc., Upper Saddle River, New Jersey.]
35.1 Introduction to Python (Continued)
Python statements can be executed in two ways. The first is by typing statements into a file (as in Fig. 35.1). Python files typically end with .py, although other extensions (e.g., .pyw on Windows) can be used. Python is then invoked on the file by typing
at the command line, where file.py is the name of the Python file. [Note: To invoke Python, the system's PATH variable must be set properly to include the python executable. If you installed ActivePython, the appropriate variable should already be set. If you are using a different version of Python, please consult its documentation for information on setting up the correct variable.] The output box of Fig. 35.1 contains the results of invoking Python on fig35_01.py.
Python statements can also be interpreted interactively. Typing
at the command prompt runs Python in interactive mode.
Error-Prevention Tip 35.1
In interactive mode, Python statements can be entered and interpreted one at a time. This mode is often useful when debugging a program (i.e., discovering and removing errors in the program).
Figure 35.2 shows Python running in interactive mode on Windows. The first two lines display information about the version of Python being used. The third line begins with the Python prompt (>>>). A Python statement is interpreted by typing the statement at the Python prompt and pressing the Enter or Return key.
Fig. 35.2 Python in interactive mode.
Python 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
>>> print "Welcome to Python!"
Welcome to Python!
The print statement on the third line prints the text Welcome to Python! to the screen. After printing the text to the screen, the Python prompt is displayed again (line 5), and Python waits for the user to enter the next statement. We exit Python by typing Crtl-Z (on Microsoft Windows systems) and pressing the Return key. [Note: On UNIX and Linux systems, Ctrl-D exits Python.]