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.
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 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.
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 #
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
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 #
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
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
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 #! mechanism.
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.
Comment:
Python is not just found in /usr/local. On my system it is in /usr/bin. I suggest changing the intro a bit.
Posted by infogami
Comment:
I have re-written the first paragraph to reflect the situation that Python now comes pre-installed most of the time and that many Python users are on windows. It is now slightly longer. Maybe we can just leave out the bit about the PATH, since people who do not know how to start a program from the command line will probably not know how to change the search path either and we should direct them to the admin directly.
Posted by infogami
Comment:
Would anyone miss the "The Interactive Startup File" section if it was removed, or moved to an appendix?
Posted by infogami
Comment:
I wouldn't miss the "Interactive Startup File" section. Acually I wouldn't miss the entire "The Interpreter and Its Environment" section. At this point the reader is assumed to be eager to start writing rudimentary Python, and will probably skip the entire section anyway.
Posted by infogami
Comment:
It might be worth mentioning one of the online Python interpreters for people who want to have a go without installing anything.
Posted by infogami
Comment:
I added the "Do You have Python?" section. It was too presumptuous to assume the reader already has Python. Also I updated Invoking the Interpreter section to *tell it like it is* - people only want 2 things when learning Python: 1. The simple interactive prompt (testing examples, playing around) 2. The simple 'run my script' technique (same as above) Anything else only adds to clutter - I don't know of any new user who wanted to use -m (or even -c, when it easier to test interactively) options, I suggest they be removed. This is not a reference for command line options.
Posted by infogami
Comment:
You are right, it is important to note that encodings are an issue. Still, the Source Code Encoding section feel completely out of place here. How about having only a short comment on encodings being an issue in this chapter, with a link to the full encoding explaination (which will reside elsewhere)? This way most readers (who will use plain english) will be warned not to use other encodings, and those interested can go read more.
Posted by infogami
Comment:
"I've never used the encoding, is it really useful for the tutorial?" Since Python 2.5 treats non-ASCII characters as a fatal error if there's no coding directive, it's pretty much required reading for anyone who wants to write anything but english. I agree with the rest of your comments, though.
Posted by infogami
Comment:
There are now two sections 'Interactive mode'. I'd say make that one, and insert the first part of the next chapter there. Let them play with the calculator first, then explain that you can save a file and run that. Maybe that would make this chapter 'Your first interactive session', and then explain the files, how to run them, and possibly the encoding. I've never used the encoding, is it really useful for the tutorial?
Posted by infogami
Comment:
Thanks! I've made some minor copy edits, and changed the part about 2.5 division being different; as Baseline pointed out in an inline comment, the division change is a Python 3000 thing.
Posted by infogami
Comment:
I've implemented some changes. Lack the time tonight to improve it further. So, I'll see who picks it up before I get a chance again.
Posted by infogami
Comment:
More editing! Thanks for the previous feedback. Didn't know when the division was going to change, didn't read about it in the "Whats new in 2.5" document, but if I left it out, and it was in 2.5, it would perhaps be forgotten to be added. And I did get to experiment with the __future__! :) I split the edits up into a few different edit-sessions, because I was wondering whether some changes are actually a good idea, so this way I think it's easier to undo. Let me know if it's annoying. And anyone can look at the fixme's and the questions ofcourse!
Posted by infogami
Comment:
help(), absolutely. It might be too early to mention dir() (since neither modules nor classes have been introduced yet). As for an overhaul, "crisn" has been working on a restructuring, but I think he's been checking things in after each iteration. But if "extensive" means "radically changed", I suggest doing a temporary fork; create a [node4-lac.html](node4-lac.html) with your new version, use a COMMENT tag to link to it (cf. the [classes](node11.html) chapter), and replace/merge back after you've gotten enough feedback.
Posted by infogami
Comment:
I think we should mention help() and dir() in this section. Actually, I would like to take a bash at extensively editing this page. With this collide with somebody's editing in progress?
Posted by infogami
Comment:
I was finished with my changes for now. The help() command gives (for people at this stage of the tutorial) not very much helpful text I think. help print gives the EBNF notation on my system. Wouldn't it be better if it's presented later?
Posted by infogami
Comment:
Have added a reference to the Beginning Python 3-part video series over at ShowMeDo.com. The first video in the sequence (Downloading Python) is out of date and needs to be re-recorded, the other two should be quite useful to first-time users.
Posted by infogami
Comment:
Major Suggestion: How about endorsing IDLE as the interpreter to work with on this tutorial? From my experience teaching Python, using IDLE makes learning easier and makes teaching more straightforward. I may be biased (as an IDLE fan and developer) but trying to be objective, there are real advantages: 1. It comes with all Python distributions as part of the standard library, and is easy to find and run 2. Easily save an interactive session to a file or print it 3. Edit files in IDLE and execute them in the IDLE's shell with a hit of a button (F5 or Run->Run Module) - if IDLE is run with a subprocess, using this feature restarts the shell every time - this saves import headaches which are especially painful to new users, and simplifies the tutorial since we don't have to explain these issues early on 4. Interpreter with syntax coloring - saves frustration from syntax errors (you see when you don't close parenthesis or string quotes, or when your indentation is bad) + helps build good habits (i.e. not naming lists "list") For example, see the comments for part 6 under [Tutorial Structure](structure) - running Python from files can be explained very simply if the tutorial endorses using IDLE, so we can leave explaining modules for later. TBH, as it is today IDLE still has a few quirks which can make working with it -slightly- awkward for a newbie. These range from minor quirks (highlighting bugs) to not-so-minor ones (can't open multiple instances which each have a subprocess, Run Module doesn't do anything without a subprocess because of singe import, major indentation bug). Still, these are just quirks, and they can all be easily solved. Actually, most have been solved in Idle-Spoon (a fork of the IDLE project), and these will probably get into the core Python version for 2.6. Even with these quirks, I think explaining how to work with IDLE (and get around its quirks) will be beneficial. It will both allow the tutorial to start with basic concepts and leave technical issues for later, and give the learner a simple, clean, and friendly environment to learn in. What do you say?
Posted by infogami

Comment:
For 2.5+ should list quit()/exit() in preference to the other options?
Posted by infogami