Using the Python Interpreter
COMMENT: Original Source
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.
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 to a file 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 >>>
Let’s start with some arithmetic first, because Python can do that easily too.
>>> 2+2 4 >>> 3*4 12 >>> 2+2*3 8 >>> (2+2)*3 12
Computers can do division too, but you have to be a little careful when using it. In Python, if you divide two integers, Python will round the result down to the nearest integer:
>>> 3 / 4 0
However, if you add a decimal part to a number, Python treats this as a floating point number, and uses floating point division instead:
>>> 3.0 / 4 0.75 >>> 3 / 4.0 0.75 >>> 3.0 / 4.0 0.75
The interpreter prints up to seventeen significant digits when it prints a floating point number, which can cause surprises when you print out decimal values that cannot be exactly represented by the internal binary representation. For example, the decimal value 0.1 ends up with more decimals than one would expect:
>>> 1.0 / 10.0 0.10000000000000001
For more on this, see Appendix B, Floating Point Arithmetic: Issues and Limitations.
Python works with strings as well:
>>> 'hello ' + 'world' 'hello world'
We’ll get back to more things to do at the interactive prompt later in this tutorial.
Exiting the Interpreter
Typing an end-of-file character (Control-D on Unix and Mac OS X, Control-Z followed by Return on Windows) at the primary prompt causes the interpreter to exit with a zero exit status.
>>> exit() $
If none of the above works, you can try typing the following commands:
import sys; sys.exit()
More About the Interactive Mode
Using python interactive like this is very convenient and useful. To get even more done interactively, we’ll tell 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
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? ]
When an error occurs, the interpreter prints an error message and a stack trace. This tells you which error occured where. In interactive mode, it then returns to the primary prompt; when input came from a file, it exits with a nonzero exit status after printing the stack trace. Some errors are unconditionally fatal and cause an exit with a nonzero exit; this applies to internal inconsistencies and some cases of running out of memory. Normally this shouldn’t happen though. [ QUESTION: Should we even mention these fatal errors here?] All error messages are written to the standard error stream; normal output from executed commands is written to standard output. [ QUESTION: Should we mention stderr and stdout? ]
Typing the system’s interrupt character (usually Control-C or DEL) to the primary or secondary prompt cancels the input and returns to the primary prompt. Typing an interrupt while a command is executing raises a KeyboardInterrupt exception, which may be handled by a try statement.
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 a 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
-i before the script. When we run the previous script
like this we get:
$ python -i ./myscript.py hello 10 >>> print a - 2 8
Source Code Encoding
It is possible to use encodings different than ASCII in Python source files. The best way to do it is to put one more special comment line right after the “#!” line to define the source file encoding:
# -*- coding: _encoding_ -*-
With that declaration, all characters in the source file will be treated as having the given encoding, and you can use non-ASCII text in Unicode string literals. The list of possible encodings can be found in the Python Library Reference, in the section on codecs.
For example, to write Unicode literals including the Euro currency symbol, the ISO-8859-15 encoding can be used, with the Euro symbol having the ordinal value 164. This script will print the value 8364 (the Unicode codepoint corresponding to the Euro symbol) and then exit:
# -*- coding: iso-8859-15 -*- currency = u"€" print ord(currency)
If your editor supports saving files as UTF-8 with a byte order mark
(BOM), you can use that instead of an encoding declaration. IDLE
supports this capability if `Options/General/Default Source
Encoding/UTF-8` is set. Note that older versions of Python (2.2 and
earlier) don’t understand the BOM, and it also doesn’t work with
executable scripts that uses the
By using UTF-8 (either through the signature or an encoding declaration), characters of most languages in the world can be used simultaneously in string literals and comments. Using non-ASCII characters in identifiers is not supported. To display all these characters properly, your editor must recognize that the file is UTF-8, and it must use a font that supports all the characters in the file.