Beginners - Using the Python Interpreter
last updated 2 years ago by gerard #
Do you have Python?
To check if Python is already installed on your system, try to invoke the interpreter as described in the next section. Python comes pre-installed on recent Mac OS X systems (10.2 Jaguar and newer) and many Linux distributions. If you need to install Python, you can download the latest version from http://www.python.org/download.
Starting Python
You can run Python in an interactive mode, which lets you type in Python code line by line, and have it executed immediately, or you can have Python execute saved programs (usually saved with the ".py" extension). For this tutorial we start with an interactive session, because it's such a wonderful feature!
To start Python in interactive mode:
UNIX-like system: Open a terminal window (like gnome-terminal, konsole, or xterm) and type 'python' at the prompt.
Windows: Click on the Start -> All Programs -> Python 2.4 -> Python (command line) or Python IDLE. IDLE is more convenient, the command line version looks more like the UNIX version.
Mac OS X: Open a Terminal window, and type 'python' at the prompt.
Once you have done that, you should see something like this:
$ python
Python 2.4.2 (#2, Sep 30 2005, 21:19:01)
[GCC 4.0.2 20050808 (prerelease) (Ubuntu 4.0.1-4ubuntu8)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
The banner tells you which version of Python you're using. Below that, you see the prompt (">>> ") which tells you the interpreter is waiting for you to type something.
In the following examples, the ">>>" and "..." prompts you see at the start of a line are printed by the interpreter - you do not have to type those! To repeat the example, type in everything you see after the prompt. The "..." prompt on a line by itself in an example means you must type a blank line; this is used to end a multi-line command.
Any line not starting with a prompt is the output of the interpreter.
So, let's type something!
>>> print 'Hello World'
Hello World
>>>
Python can be used as a calculator too. Try some basic arithmetic:
>>> 2+2
4
>>> 2-2
0
>>> 3*4
12
>>> 2+2*3
8
>>> (2+2)*3
12
Be careful with division though. In Python, if you divide two whole numbers (numbers without a decimal point), then the result is rounded down:
>>> 3 / 4
0
This is often the behaviour you want, but if you do want an exact answer, then simply include the decimal point in one of the numbers you want to divide:
>>> 3.0 / 4
0.75
We'll see more examples of using Python as a calculator in the next chapter.
Exiting the Interpreter
If you want to exit the interpreter, type Control-D on Unix and Mac OS X, and Control-Z followed by Return on Windows.
In Python 2.5, you can also use exit() or quit() to exit the interpreter.
>>> exit()
$
If none of the above works, you can try typing the following commands:
import sys; sys.exit()
More About the Interactive Mode
In interactive mode mode the interpreter prompts for the next command with the primary prompt, usually three greater-than signs (">>> "); for continuation lines it prompts with the secondary prompt, by default three dots ("... "). Continuation lines are needed when entering a multi-line construct. As an example, take a look at this if statement:
>>> the_world_is_flat = True
>>> if the_world_is_flat:
... print "Be careful not to fall off!"
...
Be careful not to fall off!
The interpreter's line-editing features usually aren't very sophisticated. On Unix, whoever installed the interpreter may have enabled support for the GNU readline library, which adds more elaborate interactive editing and history features. Perhaps the quickest check to see whether command line editing is supported is typing Control-P, or the up-arrow to the first Python prompt you get. If it beeps, you have command line editing; see Appendix A for an introduction to the keys. If nothing appears to happen, or if P is echoed, command line editing isn't available; you'll only be able to use backspace to remove characters from the current line. [ FIXME: Tell more about the up-arrow? ]
Error Handling
[ Example of a typical error: ValueError or 'DivideByZero' error. Short description of a stack trace. Mention exit status? ]
Running Saved Programs
You can of course also save your program so you can run it again at any time.
To run a Python program from a file, pass the ".py" file name to the interpreter, for example:
$ python myprogram.py
Under windows, you can give the file an extension of ".py" or ".pyw" and then you can just double-click on it. The .py will open a console (a black window) where your output (print commands for example) will appear. The ".pyw" extension will not show any output, so you have to build a user-interface yourself.
Executable Python Scripts
On most Unix systems, Python scripts can be made directly executable, like shell scripts, by putting the line
#! /usr/bin/env python
(assuming that the interpreter is on the user's PATH) at the beginning of the script and giving the file an executable mode. The "#!" must be the first two characters of the file. On some platforms, this first line must end with a Unix-style line ending ("\n"). Note that the hash character, "#", is used to start a comment in Python.
The script can be given an executable mode, or permission, using the chmod command:
$ more myscript.py
#! /usr/bin/env python
print "hello"
a = 10
print a
$ chmod +x myscript.py
$ ./myscript.py
hello
10
When a script file is used, it is sometimes useful to be able to run the script and enter interactive mode afterwards. This can be done by passing -i before the script. When we run the previous script like this we get:
$ python -i ./myscript.py
hello
10
>>> print a - 2
8
