Try Python - a Python statement evaluator


Usage

Just type Python statements into the console window. If you are entering text at the end of the console and hit return, the last line will be evaluated, and the results will be printed. While most statements — print, import and assignment — work, you can't define functions or classes (yet, I hope).

The anchors on this page will open or close bits of documentation on Python or Try Python, helping to guide you through the various things you can do with Python, or about the page.

Throughout this page, input and output are distinguished by the presence or absence of prompts (">>" and "... "): to repeat the example, you must type everything after the prompt, when the prompt appears; lines that do not begin with a prompt are output from the interpreter. Note that a secondary 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.

Help

Python has a built-in help system. You can ask for help on pretty much any name you see by typing help(name) in the console window. For instance, you can get documentation on the builtin functions by doing help(function), so help(len) will tell you about the builtin len function.

Numbers

The interpreter acts as a simple calculator: you can type an expression at it and it will write the value. Expression syntax is straightforward: the operators +, -, * and / work just like in most other languages (for example, Pascal or C); parentheses can be used for grouping. For example:


>>> 2+2
4
>>> # This is a comment
>>> 2+2  # and a comment on the same line as code
4
>>> (50-5*6)/4
5
>>> 7/3  # Integer division returns the floor:
2
>>> 7/-3
-3

The equal sign ("=") is used to assign a value to a variable. Afterwards, no result is displayed before the next interactive prompt:


>>> width = 20
>>> height = 5*9
>>> width * height
900

A value can be assigned to several variables simultaneously:


>>> x = y = z = 0  # Zero x, y and z
>>> x
0
>>> y
0
>>> z
0

There is full support for floating point; operators with mixed type operands convert the integer operand to floating point:


>>> 3 * 3.75 / 1.5
7.5
>>> 7.0 / 2
3.5

Complex numbers are also supported; imaginary numbers are written with a suffix of "j" or "J". Complex numbers with a nonzero real component are written as "(real+imagj)", or can be created with the "complex(real, imag)" function.


>>> 1j * 1J
(-1+0j)
>>> 1j * complex(0,1)
(-1+0j)
>>> 3+1j*3
(3+3j)
>>> (3+1j)*3
(9+3j)
>>> (1+2j)/(1+1j)
(1.5+0.5j)

Complex numbers are always represented as two floating point numbers, the real and imaginary part. To extract these parts from a complex number z, use z.real and z.imag.


>>> a=1.5+0.5j
>>> a.real
1.5
>>> a.imag
0.5

The conversion functions to floating point and integer (float(), int() and long()) don't work for complex numbers -- there is no one correct way to convert a complex number to a real number. Use abs(z) to get its magnitude (as a float) or z.real to get its real part.


>>> a=3.0+4.0j
>>> float(a)
TypeError: can't convert complex to float; use abs(z)
>>> a.real
3.0
>>> a.imag
4.0
>>> abs(a)  # sqrt(a.real**2 + a.imag**2)
5.0

In interactive mode, the last printed expression is assigned to the variable _. This means that when you are using Python as a desk calculator, it is somewhat easier to continue calculations, for example:


>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06
>>>

This variable should be treated as read-only by the user. Don't explicitly assign a value to it -- you would create an independent local variable with the same name masking the built-in variable with its magic behavior.

Strings

Besides numbers, Python can also manipulate strings, which can be expressed in several ways. They can be enclosed in single quotes or double quotes:


>>> 'spam eggs'
'spam eggs'
>>> 'doesn\'t'
"doesn't"
>>> "doesn't"
"doesn't"
>>> '"Yes," he said.'
'"Yes," he said.'
>>> "\"Yes,\" he said."
'"Yes," he said.'
>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'

String literals can span multiple lines in several ways. Continuation lines can be used, with a backslash as the last character on the line indicating that the next line is a logical continuation of the line:


hello = "This is a rather long string containing\n\
several lines of text just as you would do in C.\n\
    Note that whitespace at the beginning of the line is\
 significant."

print hello

Note that newlines still need to be embedded in the string using \n; the newline following the trailing backslash is discarded. This example would print the following:


This is a rather long string containing
several lines of text just as you would do in C.
    Note that whitespace at the beginning of the line is significant.

If we make the string literal a ``raw'' string, however, the \n sequences are not converted to newlines, but the backslash at the end of the line, and the newline character in the source, are both included in the string as data. Thus, the example:


hello = r"This is a rather long string containing\n\
several lines of text much as you would do in C."

print hello

would print:


This is a rather long string containing\n\
several lines of text much as you would do in C.

Or, strings can be surrounded in a pair of matching triple-quotes: """ or '''. End of lines do not need to be escaped when using triple-quotes, but they will be included in the string.


print """
Usage: thingy [OPTIONS] 
     -h                        Display this usage message
     -H hostname               Hostname to connect to
"""

produces the following output:


Usage: thingy [OPTIONS] 
     -h                        Display this usage message
     -H hostname               Hostname to connect to

The interpreter prints the result of string operations in the same way as they are typed for input: inside quotes, and with quotes and other funny characters escaped by backslashes, to show the precise value. The string is enclosed in double quotes if the string contains a single quote and no double quotes, else it's enclosed in single quotes.

Strings can be concatenated (glued together) with the + operator, and repeated with *:


>>> word = 'Help' + 'A'
>>> word
'HelpA'
>>> '<' + word*5 + '>'
'<HelpAHelpAHelpAHelpAHelpA>'

Two string literals next to each other are automatically concatenated; the first line above could also have been written "'Help' 'A'"; this only works with two literals, not with arbitrary string expressions:


>>> 'str' 'ing'             #  <-  This is ok
'string'
>>> 'str'.strip() + 'ing'   #  <-  This is ok
'string'
>>> 'str'.strip() 'ing'     #  <-  This is invalid
SyntaxError: invalid syntax (line 1)

Strings can be subscripted (indexed); like in C, the first character of a string has subscript (index) 0. There is no separate character type; a character is simply a string of size one. Like in Icon, substrings can be specified with the slice notation: two indices separated by a colon.


>>> word[4]
'A'
>>> word[0:2]
'He'
>>> word[2:4]
'lp'

Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.


>>> word[:2]    # The first two characters
'He'
>>> word[2:]    # Everything except the first two characters
'lpA'

Unlike a C string, Python strings cannot be changed. Assigning to an indexed position in the string results in an error:


>>> word[0] = 'x'
TypeError: object doesn't support item assignment
>>> word[:1] = 'Splat'
TypeError: object doesn't support slice assignment

However, creating a new string with the combined content is easy and efficient:


>>> 'x' + word[1:]
'xelpA'
>>> 'Splat' + word[4]
'SplatA'

Here's a useful invariant of slice operations: s[:i] + s[i:] equals s.


>>> word[:2] + word[2:]
'HelpA'
>>> word[:3] + word[3:]
'HelpA'

Degenerate slice indices are handled gracefully: an index that is too large is replaced by the string size, an upper bound smaller than the lower bound returns an empty string.


>>> word[1:100]
'elpA'
>>> word[10:]
''
>>> word[2:1]
''

Indices may be negative numbers, to start counting from the right. For example:


>>> word[-1]     # The last character
'A'
>>> word[-2]     # The last-but-one character
'p'
>>> word[-2:]    # The last two characters
'pA'
>>> word[:-2]    # Everything except the last two characters
'Hel'

But note that -0 is really the same as 0, so it does not count from the right!


>>> word[-0]     # (since -0 equals 0)
'H'

Out-of-range negative slice indices are truncated, but don't try this for single-element (non-slice) indices:


>>> word[-100:]
'HelpA'
>>> word[-10]    # error
IndexError: string index out of range

The best way to remember how slices work is to think of the indices as pointing between characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string of n characters has index n, for example:


 +---+---+---+---+---+ 
 | H | e | l | p | A |
 +---+---+---+---+---+ 
 0   1   2   3   4   5 
-5  -4  -3  -2  -1

The first row of numbers gives the position of the indices 0...5 in the string; the second row gives the corresponding negative indices. The slice from i to j consists of all characters between the edges labeled i and j, respectively.

For non-negative indices, the length of a slice is the difference of the indices, if both are within bounds. For example, the length of word[1:3] is 2.

The built-in function len() returns the length of a string:


>>> len('supercalifragilisticexpialidocious')
34

More information

This tool is limited in that you can't define functions for technical reasons. While you can do quite a lot with python inside this restriction, you can't really program this way. If you want to try a little Python programming, check out Devan L's online Python tool.

For more information in general - manuals, FAQs, forums, etc. - see the Python web site.

Getting Python

You can get a Windows binary for Python from python.org.

Recent versions of Mac OS X come with Python pre-installed. You can access it by launching Applications > Utilities > Terminal, and running the command python in the resulting console window. However, it's an older version of Python, and older versions of OS X may not have it installed. In that case, you can get a current Python binary for OS X from python.org.

Most Linux systems come with Python pre-installed; just type python at the command prompt, and it should present you with the >>> prompt you see in the console above. If you want to get a more recent version, it's possible to install a version from python.org alongside the pre-installed version. Do not overwrite the pre-installed version of Python!

BSD systems usually have Python available as a port; you can just install the port or package on your system. You can also get the sources from python.org and build it yourself.

There is a version of Python available for Symbian-based smartphones. You'll have to register to download it, but the registration and download are both free.

Other systems probably have a Python package available as well, just check the open source package repositories for your system. If all else fails, you can get the sources from python.org and build it yourself. A wide variety of platforms are supported, and building it is usually straightforward.

Problems

General problems

  • Some of the available Python utilities expect to read from standard input. This won't work, and using them will cause an exception or an early exit from that facility.
  • Variables are kept in a Python pickle. Some objects can't be pickled. If you assign such an object to a variable, it will cause the pickling to fail, and none of the objects created on that line will be kept.

Browser specific problems

  • Try Python works, but doesn't track the end of the text area in:

    • Safari
    • Shiira
    • OmniWeb

    There's apparently no way to fix this. Suggestions welcome.

  • Opera doesn't seem to get the repsonse back.

Reporting problems

Report problems to Mike Meyer.

Security

Yeah, there's lots of ways to get to the os module. I'm not even going to try and keep you from it. For those who want it, the following will get you a complete list of all the writable files available to you:


for d, _, fn in os.walk('/'):
    for f in fn:
        n = os.path.join(d, f)
        if os.access(n, os.W_OK):
            print n

You'll notice there isn't much there. My ISP (idiom.com) provides a sandbox inside a FreeBSD Jail, so all you'll find are the script, the Python executables, the script and Python library.