3
**********************************
4
An Informal Introduction to Python
5
**********************************
7
In the following examples, input and output are distinguished by the presence or
8
absence of prompts (``>>>`` and ``...``): to repeat the example, you must type
9
everything after the prompt, when the prompt appears; lines that do not begin
10
with a prompt are output from the interpreter. Note that a secondary prompt on a
11
line by itself in an example means you must type a blank line; this is used to
12
end a multi-line command.
14
Many of the examples in this manual, even those entered at the interactive
15
prompt, include comments. Comments in Python start with the hash character,
16
``#``, and extend to the end of the physical line. A comment may appear at the
17
start of a line or following whitespace or code, but not within a string
18
literal. A hash character within a string literal is just a hash character.
19
Since comments are to clarify code and are not interpreted by Python, they may
20
be omitted when typing in examples.
24
# this is the first comment
25
SPAM = 1 # and this is the second comment
26
# ... and now a third!
27
STRING = "# This is not a comment."
32
Using Python as a Calculator
33
============================
35
Let's try some simple Python commands. Start the interpreter and wait for the
36
primary prompt, ``>>>``. (It shouldn't take long.)
44
The interpreter acts as a simple calculator: you can type an expression at it
45
and it will write the value. Expression syntax is straightforward: the
46
operators ``+``, ``-``, ``*`` and ``/`` work just like in most other languages
47
(for example, Pascal or C); parentheses can be used for grouping. For example::
51
>>> # This is a comment
54
>>> 2+2 # and a comment on the same line as code
58
>>> # Integer division returns the floor:
64
The equal sign (``'='``) is used to assign a value to a variable. Afterwards, no
65
result is displayed before the next interactive prompt::
72
A value can be assigned to several variables simultaneously::
74
>>> x = y = z = 0 # Zero x, y and z
82
Variables must be "defined" (assigned a value) before they can be used, or an
85
>>> # try to access an undefined variable
87
Traceback (most recent call last):
88
File "<stdin>", line 1, in <module>
89
NameError: name 'n' is not defined
91
There is full support for floating point; operators with mixed type operands
92
convert the integer operand to floating point::
99
Complex numbers are also supported; imaginary numbers are written with a suffix
100
of ``j`` or ``J``. Complex numbers with a nonzero real component are written as
101
``(real+imagj)``, or can be created with the ``complex(real, imag)`` function.
106
>>> 1j * complex(0,1)
115
Complex numbers are always represented as two floating point numbers, the real
116
and imaginary part. To extract these parts from a complex number *z*, use
117
``z.real`` and ``z.imag``. ::
125
The conversion functions to floating point and integer (:func:`float`,
126
:func:`int` and :func:`long`) don't work for complex numbers --- there is no one
127
correct way to convert a complex number to a real number. Use ``abs(z)`` to get
128
its magnitude (as a float) or ``z.real`` to get its real part. ::
132
Traceback (most recent call last):
133
File "<stdin>", line 1, in ?
134
TypeError: can't convert complex to float; use abs(z)
139
>>> abs(a) # sqrt(a.real**2 + a.imag**2)
143
In interactive mode, the last printed expression is assigned to the variable
144
``_``. This means that when you are using Python as a desk calculator, it is
145
somewhat easier to continue calculations, for example::
157
This variable should be treated as read-only by the user. Don't explicitly
158
assign a value to it --- you would create an independent local variable with the
159
same name masking the built-in variable with its magic behavior.
167
Besides numbers, Python can also manipulate strings, which can be expressed in
168
several ways. They can be enclosed in single quotes or double quotes::
176
>>> '"Yes," he said.'
178
>>> "\"Yes,\" he said."
180
>>> '"Isn\'t," she said.'
181
'"Isn\'t," she said.'
183
String literals can span multiple lines in several ways. Continuation lines can
184
be used, with a backslash as the last character on the line indicating that the
185
next line is a logical continuation of the line::
187
hello = "This is a rather long string containing\n\
188
several lines of text just as you would do in C.\n\
189
Note that whitespace at the beginning of the line is\
194
Note that newlines still need to be embedded in the string using ``\n``; the
195
newline following the trailing backslash is discarded. This example would print
198
This is a rather long string containing
199
several lines of text just as you would do in C.
200
Note that whitespace at the beginning of the line is significant.
202
If we make the string literal a "raw" string, however, the ``\n`` sequences are
203
not converted to newlines, but the backslash at the end of the line, and the
204
newline character in the source, are both included in the string as data. Thus,
207
hello = r"This is a rather long string containing\n\
208
several lines of text much as you would do in C."
214
This is a rather long string containing\n\
215
several lines of text much as you would do in C.
217
Or, strings can be surrounded in a pair of matching triple-quotes: ``"""`` or
218
``'''``. End of lines do not need to be escaped when using triple-quotes, but
219
they will be included in the string. ::
222
Usage: thingy [OPTIONS]
223
-h Display this usage message
224
-H hostname Hostname to connect to
227
produces the following output::
229
Usage: thingy [OPTIONS]
230
-h Display this usage message
231
-H hostname Hostname to connect to
233
The interpreter prints the result of string operations in the same way as they
234
are typed for input: inside quotes, and with quotes and other funny characters
235
escaped by backslashes, to show the precise value. The string is enclosed in
236
double quotes if the string contains a single quote and no double quotes, else
237
it's enclosed in single quotes. (The :keyword:`print` statement, described
238
later, can be used to write strings without quotes or escapes.)
240
Strings can be concatenated (glued together) with the ``+`` operator, and
241
repeated with ``*``::
243
>>> word = 'Help' + 'A'
246
>>> '<' + word*5 + '>'
247
'<HelpAHelpAHelpAHelpAHelpA>'
249
Two string literals next to each other are automatically concatenated; the first
250
line above could also have been written ``word = 'Help' 'A'``; this only works
251
with two literals, not with arbitrary string expressions::
253
>>> 'str' 'ing' # <- This is ok
255
>>> 'str'.strip() + 'ing' # <- This is ok
257
>>> 'str'.strip() 'ing' # <- This is invalid
258
File "<stdin>", line 1, in ?
261
SyntaxError: invalid syntax
263
Strings can be subscripted (indexed); like in C, the first character of a string
264
has subscript (index) 0. There is no separate character type; a character is
265
simply a string of size one. Like in Icon, substrings can be specified with the
266
*slice notation*: two indices separated by a colon. ::
275
Slice indices have useful defaults; an omitted first index defaults to zero, an
276
omitted second index defaults to the size of the string being sliced. ::
278
>>> word[:2] # The first two characters
280
>>> word[2:] # Everything except the first two characters
283
Unlike a C string, Python strings cannot be changed. Assigning to an indexed
284
position in the string results in an error::
287
Traceback (most recent call last):
288
File "<stdin>", line 1, in ?
289
TypeError: object doesn't support item assignment
290
>>> word[:1] = 'Splat'
291
Traceback (most recent call last):
292
File "<stdin>", line 1, in ?
293
TypeError: object doesn't support slice assignment
295
However, creating a new string with the combined content is easy and efficient::
299
>>> 'Splat' + word[4]
302
Here's a useful invariant of slice operations: ``s[:i] + s[i:]`` equals ``s``.
305
>>> word[:2] + word[2:]
307
>>> word[:3] + word[3:]
310
Degenerate slice indices are handled gracefully: an index that is too large is
311
replaced by the string size, an upper bound smaller than the lower bound returns
321
Indices may be negative numbers, to start counting from the right. For example::
323
>>> word[-1] # The last character
325
>>> word[-2] # The last-but-one character
327
>>> word[-2:] # The last two characters
329
>>> word[:-2] # Everything except the last two characters
332
But note that -0 is really the same as 0, so it does not count from the right!
335
>>> word[-0] # (since -0 equals 0)
338
Out-of-range negative slice indices are truncated, but don't try this for
339
single-element (non-slice) indices::
343
>>> word[-10] # error
344
Traceback (most recent call last):
345
File "<stdin>", line 1, in ?
346
IndexError: string index out of range
348
One way to remember how slices work is to think of the indices as pointing
349
*between* characters, with the left edge of the first character numbered 0.
350
Then the right edge of the last character of a string of *n* characters has
351
index *n*, for example::
353
+---+---+---+---+---+
354
| H | e | l | p | A |
355
+---+---+---+---+---+
359
The first row of numbers gives the position of the indices 0...5 in the string;
360
the second row gives the corresponding negative indices. The slice from *i* to
361
*j* consists of all characters between the edges labeled *i* and *j*,
364
For non-negative indices, the length of a slice is the difference of the
365
indices, if both are within bounds. For example, the length of ``word[1:3]`` is
368
The built-in function :func:`len` returns the length of a string::
370
>>> s = 'supercalifragilisticexpialidocious'
378
Strings, and the Unicode strings described in the next section, are
379
examples of *sequence types*, and support the common operations supported
382
:ref:`string-methods`
383
Both strings and Unicode strings support a large number of methods for
384
basic transformations and searching.
386
:ref:`new-string-formatting`
387
Information about string formatting with :meth:`str.format` is described
390
:ref:`string-formatting`
391
The old formatting operations invoked when strings and Unicode strings are
392
the left operand of the ``%`` operator are described in more detail here.
395
.. _tut-unicodestrings:
400
.. sectionauthor:: Marc-Andre Lemburg <mal@lemburg.com>
403
Starting with Python 2.0 a new data type for storing text data is available to
404
the programmer: the Unicode object. It can be used to store and manipulate
405
Unicode data (see http://www.unicode.org/) and integrates well with the existing
406
string objects, providing auto-conversions where necessary.
408
Unicode has the advantage of providing one ordinal for every character in every
409
script used in modern and ancient texts. Previously, there were only 256
410
possible ordinals for script characters. Texts were typically bound to a code
411
page which mapped the ordinals to script characters. This lead to very much
412
confusion especially with respect to internationalization (usually written as
413
``i18n`` --- ``'i'`` + 18 characters + ``'n'``) of software. Unicode solves
414
these problems by defining one code page for all scripts.
416
Creating Unicode strings in Python is just as simple as creating normal
422
The small ``'u'`` in front of the quote indicates that a Unicode string is
423
supposed to be created. If you want to include special characters in the string,
424
you can do so by using the Python *Unicode-Escape* encoding. The following
427
>>> u'Hello\u0020World !'
430
The escape sequence ``\u0020`` indicates to insert the Unicode character with
431
the ordinal value 0x0020 (the space character) at the given position.
433
Other characters are interpreted by using their respective ordinal values
434
directly as Unicode ordinals. If you have literal strings in the standard
435
Latin-1 encoding that is used in many Western countries, you will find it
436
convenient that the lower 256 characters of Unicode are the same as the 256
437
characters of Latin-1.
439
For experts, there is also a raw mode just like the one for normal strings. You
440
have to prefix the opening quote with 'ur' to have Python use the
441
*Raw-Unicode-Escape* encoding. It will only apply the above ``\uXXXX``
442
conversion if there is an uneven number of backslashes in front of the small
445
>>> ur'Hello\u0020World !'
447
>>> ur'Hello\\u0020World !'
448
u'Hello\\\\u0020World !'
450
The raw mode is most useful when you have to enter lots of backslashes, as can
451
be necessary in regular expressions.
453
Apart from these standard encodings, Python provides a whole set of other ways
454
of creating Unicode strings on the basis of a known encoding.
456
.. index:: builtin: unicode
458
The built-in function :func:`unicode` provides access to all registered Unicode
459
codecs (COders and DECoders). Some of the more well known encodings which these
460
codecs can convert are *Latin-1*, *ASCII*, *UTF-8*, and *UTF-16*. The latter two
461
are variable-length encodings that store each Unicode character in one or more
462
bytes. The default encoding is normally set to ASCII, which passes through
463
characters in the range 0 to 127 and rejects any other characters with an error.
464
When a Unicode string is printed, written to a file, or converted with
465
:func:`str`, conversion takes place using this default encoding. ::
474
Traceback (most recent call last):
475
File "<stdin>", line 1, in ?
476
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)
478
To convert a Unicode string into an 8-bit string using a specific encoding,
479
Unicode objects provide an :func:`encode` method that takes one argument, the
480
name of the encoding. Lowercase names for encodings are preferred. ::
482
>>> u"äöü".encode('utf-8')
483
'\xc3\xa4\xc3\xb6\xc3\xbc'
485
If you have data in a specific encoding and want to produce a corresponding
486
Unicode string from it, you can use the :func:`unicode` function with the
487
encoding name as the second argument. ::
489
>>> unicode('\xc3\xa4\xc3\xb6\xc3\xbc', 'utf-8')
498
Python knows a number of *compound* data types, used to group together other
499
values. The most versatile is the *list*, which can be written as a list of
500
comma-separated values (items) between square brackets. List items need not all
501
have the same type. ::
503
>>> a = ['spam', 'eggs', 100, 1234]
505
['spam', 'eggs', 100, 1234]
507
Like string indices, list indices start at 0, and lists can be sliced,
508
concatenated and so on::
518
>>> a[:2] + ['bacon', 2*2]
519
['spam', 'eggs', 'bacon', 4]
520
>>> 3*a[:3] + ['Boo!']
521
['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boo!']
523
Unlike strings, which are *immutable*, it is possible to change individual
527
['spam', 'eggs', 100, 1234]
530
['spam', 'eggs', 123, 1234]
532
Assignment to slices is also possible, and this can even change the size of the
533
list or clear it entirely::
535
>>> # Replace some items:
544
... a[1:1] = ['bletch', 'xyzzy']
546
[123, 'bletch', 'xyzzy', 1234]
547
>>> # Insert (a copy of) itself at the beginning
550
[123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234]
551
>>> # Clear the list: replace all items with an empty list
556
The built-in function :func:`len` also applies to lists::
558
>>> a = ['a', 'b', 'c', 'd']
562
It is possible to nest lists (create lists containing other lists), for
573
>>> p[1].append('xtra') # See section 5.1
575
[1, [2, 3, 'xtra'], 4]
579
Note that in the last example, ``p[1]`` and ``q`` really refer to the same
580
object! We'll come back to *object semantics* later.
585
First Steps Towards Programming
586
===============================
588
Of course, we can use Python for more complicated tasks than adding two and two
589
together. For instance, we can write an initial sub-sequence of the *Fibonacci*
592
>>> # Fibonacci series:
593
... # the sum of two elements defines the next
606
This example introduces several new features.
608
* The first line contains a *multiple assignment*: the variables ``a`` and ``b``
609
simultaneously get the new values 0 and 1. On the last line this is used again,
610
demonstrating that the expressions on the right-hand side are all evaluated
611
first before any of the assignments take place. The right-hand side expressions
612
are evaluated from the left to the right.
614
* The :keyword:`while` loop executes as long as the condition (here: ``b < 10``)
615
remains true. In Python, like in C, any non-zero integer value is true; zero is
616
false. The condition may also be a string or list value, in fact any sequence;
617
anything with a non-zero length is true, empty sequences are false. The test
618
used in the example is a simple comparison. The standard comparison operators
619
are written the same as in C: ``<`` (less than), ``>`` (greater than), ``==``
620
(equal to), ``<=`` (less than or equal to), ``>=`` (greater than or equal to)
621
and ``!=`` (not equal to).
623
* The *body* of the loop is *indented*: indentation is Python's way of grouping
624
statements. Python does not (yet!) provide an intelligent input line editing
625
facility, so you have to type a tab or space(s) for each indented line. In
626
practice you will prepare more complicated input for Python with a text editor;
627
most text editors have an auto-indent facility. When a compound statement is
628
entered interactively, it must be followed by a blank line to indicate
629
completion (since the parser cannot guess when you have typed the last line).
630
Note that each line within a basic block must be indented by the same amount.
632
* The :keyword:`print` statement writes the value of the expression(s) it is
633
given. It differs from just writing the expression you want to write (as we did
634
earlier in the calculator examples) in the way it handles multiple expressions
635
and strings. Strings are printed without quotes, and a space is inserted
636
between items, so you can format things nicely, like this::
639
>>> print 'The value of i is', i
640
The value of i is 65536
642
A trailing comma avoids the newline after the output::
649
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
651
Note that the interpreter inserts a newline before it prints the next prompt if
652
the last line was not completed.