In the following examples, 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.
Many of the examples in this manual, even those entered at the interactive prompt, include comments. Comments in Python start with the hash character, "#", and extend to the end of the physical line. A comment may appear at the start of a line or following whitespace or code, but not within a string literal. A hash character within a string literal is just a hash character.
Some examples:
# this is the first comment SPAM = 1 # and this is the second comment # ... and now a third! STRING = "# This is not a comment."
Let's try some simple Python commands. Start the interpreter and wait for the primary prompt, ">>> ". (It shouldn't take long.)
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 (e.g., Pascal or C);
parentheses can be used for grouping. For example:
>>> 2+2 4 >>> # This is a comment ... 2+2 4 >>> 2+2 # and a comment on the same line as code 4 >>> (50-5*6)/4 5 >>> # Integer division returns the floor: ... 7/3 2 >>> 7/-3 -3
Like in C, the equal sign ("=") is used to assign a value to a variable. The value of an assignment is not written:
>>> 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
>>> 4 * 2.5 / 3.3 3.0303030303 >>> 7.0 / 2 3.5
>>> 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)
z.real
and z.imag
.
>>> a=1.5+0.5j >>> a.real 1.5 >>> a.imag 0.5
abs(z)
to get its
magnitude (as a float) or z.real
to get its real part.
>>> a=1.5+0.5j >>> float(a) Traceback (innermost last): File "<stdin>", line 1, in ? TypeError: can't convert complex to float; use e.g. abs(z) >>> a.real 1.5 >>> abs(a) 1.58113883008
_
. This means that when you are using Python as a
desk calculator, it is somewhat easier to continue calculations, for
example:
>>> tax = 17.5 / 100 >>> price = 3.50 >>> price * tax 0.6125 >>> price + _ 4.1125 >>> round(_, 2) 4.11
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.
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. Newlines can be escaped with backslashes, e.g.:
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.\n" print hello
which 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.
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. (The print statement, described later, can be used to write strings without quotes or escapes.)
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 "word = 'Help' 'A'"; this only works with two literals, not with arbitrary string expressions:
>>> 'str' 'ing' # <- This is ok 'string' >>> string.strip('str') + 'ing' # <- This is ok 'string' >>> string.strip('str') 'ing' # <- This is invalid File "<stdin>", line 1 string.strip('str') 'ing' ^ SyntaxError: invalid syntax
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'
Unlike a C string, Python strings cannot be changed. Assigning to an indexed position in the string results in an error:
>>> word[0] = 'x' Traceback (innermost last): File "<stdin>", line 1, in ? TypeError: object doesn't support item assignment >>> word[:-1] = 'Splat' Traceback (innermost last): File "<stdin>", line 1, in ? 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[-1:] 'SplatA'
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:] # All but the first two characters 'lpA'
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] # All but 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 Traceback (innermost last): File "<stdin>", line 1 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, e.g., the length of
word[1:3]
is 2.
The built-in function len() returns the length of a string:
>>> s = 'supercalifragilisticexpialidocious' >>> len(s) 34
Python knows a number of compound data types, used to group together other values. The most versatile is the list, which can be written as a list of comma-separated values (items) between square brackets. List items need not all have the same type.
>>> a = ['spam', 'eggs', 100, 1234] >>> a ['spam', 'eggs', 100, 1234]
Like string indices, list indices start at 0, and lists can be sliced, concatenated and so on:
>>> a[0] 'spam' >>> a[3] 1234 >>> a[-2] 100 >>> a[1:-1] ['eggs', 100] >>> a[:2] + ['bacon', 2*2] ['spam', 'eggs', 'bacon', 4] >>> 3*a[:3] + ['Boe!'] ['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boe!']
Unlike strings, which are immutable, it is possible to change individual elements of a list:
>>> a ['spam', 'eggs', 100, 1234] >>> a[2] = a[2] + 23 >>> a ['spam', 'eggs', 123, 1234]
Assignment to slices is also possible, and this can even change the size of the list:
>>> # Replace some items: ... a[0:2] = [1, 12] >>> a [1, 12, 123, 1234] >>> # Remove some: ... a[0:2] = [] >>> a [123, 1234] >>> # Insert some: ... a[1:1] = ['bletch', 'xyzzy'] >>> a [123, 'bletch', 'xyzzy', 1234] >>> a[:0] = a # Insert (a copy of) itself at the beginning >>> a [123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234]
The built-in function len() also applies to lists:
>>> len(a) 8
It is possible to nest lists (create lists containing other lists), for example:
>>> q = [2, 3] >>> p = [1, q, 4] >>> len(p) 3 >>> p[1] [2, 3] >>> p[1][0] 2 >>> p[1].append('xtra') # See section 5.1 >>> p [1, [2, 3, 'xtra'], 4] >>> q [2, 3, 'xtra']
Note that in the last example, p[1]
and q
really refer to
the same object! We'll come back to object semantics later.
Of course, we can use Python for more complicated tasks than adding two and two together. For instance, we can write an initial subsequence of the Fibonacci series as follows:
>>> # Fibonacci series: ... # the sum of two elements defines the next ... a, b = 0, 1 >>> while b < 10: ... print b ... a, b = b, a+b ... 1 1 2 3 5 8
This example introduces several new features.
a
and b
simultaneously get the new values 0 and 1. On the
last line this is used again, demonstrating that the expressions on
the right-hand side are all evaluated first before any of the
assignments take place. The right-hand side expressions are evaluated
from the left to the right.
b < 10
) remains true. In Python, like in C, any non-zero
integer value is true; zero is false. The condition may also be a
string or list value, in fact any sequence; anything with a non-zero
length is true, empty sequences are false. The test used in the
example is a simple comparison. The standard comparison operators are
written the same as in C: <
(less than), >
(greater than),
==
(equal to), <=
(less than or equal to),
>=
(greater than or equal to) and !=
(not equal to).
>>> i = 256*256 >>> print 'The value of i is', i The value of i is 65536
A trailing comma avoids the newline after the output:
>>> a, b = 0, 1 >>> while b < 1000: ... print b, ... a, b = b, a+b ... 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
Note that the interpreter inserts a newline before it prints the next prompt if the last line was not completed.