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)
142 In interactive mode, the last printed expression is assigned to the variable
143 ``_``. This means that when you are using Python as a desk calculator, it is
144 somewhat easier to continue calculations, for example::
155 This variable should be treated as read-only by the user. Don't explicitly
156 assign a value to it --- you would create an independent local variable with the
157 same name masking the built-in variable with its magic behavior.
165 Besides numbers, Python can also manipulate strings, which can be expressed in
166 several ways. They can be enclosed in single quotes or double quotes::
174 >>> '"Yes," he said.'
176 >>> "\"Yes,\" he said."
178 >>> '"Isn\'t," she said.'
179 '"Isn\'t," she said.'
181 String literals can span multiple lines in several ways. Continuation lines can
182 be used, with a backslash as the last character on the line indicating that the
183 next line is a logical continuation of the line::
185 hello = "This is a rather long string containing\n\
186 several lines of text just as you would do in C.\n\
187 Note that whitespace at the beginning of the line is\
192 Note that newlines still need to be embedded in the string using ``\n``; the
193 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 Or, strings can be surrounded in a pair of matching triple-quotes: ``"""`` or
203 ``'''``. End of lines do not need to be escaped when using triple-quotes, but
204 they will be included in the string. ::
207 Usage: thingy [OPTIONS]
208 -h Display this usage message
209 -H hostname Hostname to connect to
212 produces the following output:
216 Usage: thingy [OPTIONS]
217 -h Display this usage message
218 -H hostname Hostname to connect to
220 If we make the string literal a "raw" string, ``\n`` sequences are not converted
221 to newlines, but the backslash at the end of the line, and the newline character
222 in the source, are both included in the string as data. Thus, the example::
224 hello = r"This is a rather long string containing\n\
225 several lines of text much as you would do in C."
233 This is a rather long string containing\n\
234 several lines of text much as you would do in C.
236 The interpreter prints the result of string operations in the same way as they
237 are typed for input: inside quotes, and with quotes and other funny characters
238 escaped by backslashes, to show the precise value. The string is enclosed in
239 double quotes if the string contains a single quote and no double quotes, else
240 it's enclosed in single quotes. (The :keyword:`print` statement, described
241 later, can be used to write strings without quotes or escapes.)
243 Strings can be concatenated (glued together) with the ``+`` operator, and
244 repeated with ``*``::
246 >>> word = 'Help' + 'A'
249 >>> '<' + word*5 + '>'
250 '<HelpAHelpAHelpAHelpAHelpA>'
252 Two string literals next to each other are automatically concatenated; the first
253 line above could also have been written ``word = 'Help' 'A'``; this only works
254 with two literals, not with arbitrary string expressions::
256 >>> 'str' 'ing' # <- This is ok
258 >>> 'str'.strip() + 'ing' # <- This is ok
260 >>> 'str'.strip() 'ing' # <- This is invalid
261 File "<stdin>", line 1, in ?
264 SyntaxError: invalid syntax
266 Strings can be subscripted (indexed); like in C, the first character of a string
267 has subscript (index) 0. There is no separate character type; a character is
268 simply a string of size one. Like in Icon, substrings can be specified with the
269 *slice notation*: two indices separated by a colon. ::
278 Slice indices have useful defaults; an omitted first index defaults to zero, an
279 omitted second index defaults to the size of the string being sliced. ::
281 >>> word[:2] # The first two characters
283 >>> word[2:] # Everything except the first two characters
286 Unlike a C string, Python strings cannot be changed. Assigning to an indexed
287 position in the string results in an error::
290 Traceback (most recent call last):
291 File "<stdin>", line 1, in ?
292 TypeError: object does not support item assignment
293 >>> word[:1] = 'Splat'
294 Traceback (most recent call last):
295 File "<stdin>", line 1, in ?
296 TypeError: object does not support slice assignment
298 However, creating a new string with the combined content is easy and efficient::
302 >>> 'Splat' + word[4]
305 Here's a useful invariant of slice operations: ``s[:i] + s[i:]`` equals ``s``.
308 >>> word[:2] + word[2:]
310 >>> word[:3] + word[3:]
313 Degenerate slice indices are handled gracefully: an index that is too large is
314 replaced by the string size, an upper bound smaller than the lower bound returns
324 Indices may be negative numbers, to start counting from the right. For example::
326 >>> word[-1] # The last character
328 >>> word[-2] # The last-but-one character
330 >>> word[-2:] # The last two characters
332 >>> word[:-2] # Everything except the last two characters
335 But note that -0 is really the same as 0, so it does not count from the right!
338 >>> word[-0] # (since -0 equals 0)
341 Out-of-range negative slice indices are truncated, but don't try this for
342 single-element (non-slice) indices::
346 >>> word[-10] # error
347 Traceback (most recent call last):
348 File "<stdin>", line 1, in ?
349 IndexError: string index out of range
351 One way to remember how slices work is to think of the indices as pointing
352 *between* characters, with the left edge of the first character numbered 0.
353 Then the right edge of the last character of a string of *n* characters has
354 index *n*, for example::
356 +---+---+---+---+---+
357 | H | e | l | p | A |
358 +---+---+---+---+---+
362 The first row of numbers gives the position of the indices 0...5 in the string;
363 the second row gives the corresponding negative indices. The slice from *i* to
364 *j* consists of all characters between the edges labeled *i* and *j*,
367 For non-negative indices, the length of a slice is the difference of the
368 indices, if both are within bounds. For example, the length of ``word[1:3]`` is
371 The built-in function :func:`len` returns the length of a string::
373 >>> s = 'supercalifragilisticexpialidocious'
381 Strings, and the Unicode strings described in the next section, are
382 examples of *sequence types*, and support the common operations supported
385 :ref:`string-methods`
386 Both strings and Unicode strings support a large number of methods for
387 basic transformations and searching.
389 :ref:`new-string-formatting`
390 Information about string formatting with :meth:`str.format` is described
393 :ref:`string-formatting`
394 The old formatting operations invoked when strings and Unicode strings are
395 the left operand of the ``%`` operator are described in more detail here.
398 .. _tut-unicodestrings:
403 .. sectionauthor:: Marc-Andre Lemburg <mal@lemburg.com>
406 Starting with Python 2.0 a new data type for storing text data is available to
407 the programmer: the Unicode object. It can be used to store and manipulate
408 Unicode data (see http://www.unicode.org/) and integrates well with the existing
409 string objects, providing auto-conversions where necessary.
411 Unicode has the advantage of providing one ordinal for every character in every
412 script used in modern and ancient texts. Previously, there were only 256
413 possible ordinals for script characters. Texts were typically bound to a code
414 page which mapped the ordinals to script characters. This lead to very much
415 confusion especially with respect to internationalization (usually written as
416 ``i18n`` --- ``'i'`` + 18 characters + ``'n'``) of software. Unicode solves
417 these problems by defining one code page for all scripts.
419 Creating Unicode strings in Python is just as simple as creating normal
425 The small ``'u'`` in front of the quote indicates that a Unicode string is
426 supposed to be created. If you want to include special characters in the string,
427 you can do so by using the Python *Unicode-Escape* encoding. The following
430 >>> u'Hello\u0020World !'
433 The escape sequence ``\u0020`` indicates to insert the Unicode character with
434 the ordinal value 0x0020 (the space character) at the given position.
436 Other characters are interpreted by using their respective ordinal values
437 directly as Unicode ordinals. If you have literal strings in the standard
438 Latin-1 encoding that is used in many Western countries, you will find it
439 convenient that the lower 256 characters of Unicode are the same as the 256
440 characters of Latin-1.
442 For experts, there is also a raw mode just like the one for normal strings. You
443 have to prefix the opening quote with 'ur' to have Python use the
444 *Raw-Unicode-Escape* encoding. It will only apply the above ``\uXXXX``
445 conversion if there is an uneven number of backslashes in front of the small
448 >>> ur'Hello\u0020World !'
450 >>> ur'Hello\\u0020World !'
451 u'Hello\\\\u0020World !'
453 The raw mode is most useful when you have to enter lots of backslashes, as can
454 be necessary in regular expressions.
456 Apart from these standard encodings, Python provides a whole set of other ways
457 of creating Unicode strings on the basis of a known encoding.
459 .. index:: builtin: unicode
461 The built-in function :func:`unicode` provides access to all registered Unicode
462 codecs (COders and DECoders). Some of the more well known encodings which these
463 codecs can convert are *Latin-1*, *ASCII*, *UTF-8*, and *UTF-16*. The latter two
464 are variable-length encodings that store each Unicode character in one or more
465 bytes. The default encoding is normally set to ASCII, which passes through
466 characters in the range 0 to 127 and rejects any other characters with an error.
467 When a Unicode string is printed, written to a file, or converted with
468 :func:`str`, conversion takes place using this default encoding. ::
477 Traceback (most recent call last):
478 File "<stdin>", line 1, in ?
479 UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)
481 To convert a Unicode string into an 8-bit string using a specific encoding,
482 Unicode objects provide an :func:`encode` method that takes one argument, the
483 name of the encoding. Lowercase names for encodings are preferred. ::
485 >>> u"äöü".encode('utf-8')
486 '\xc3\xa4\xc3\xb6\xc3\xbc'
488 If you have data in a specific encoding and want to produce a corresponding
489 Unicode string from it, you can use the :func:`unicode` function with the
490 encoding name as the second argument. ::
492 >>> unicode('\xc3\xa4\xc3\xb6\xc3\xbc', 'utf-8')
501 Python knows a number of *compound* data types, used to group together other
502 values. The most versatile is the *list*, which can be written as a list of
503 comma-separated values (items) between square brackets. List items need not all
504 have the same type. ::
506 >>> a = ['spam', 'eggs', 100, 1234]
508 ['spam', 'eggs', 100, 1234]
510 Like string indices, list indices start at 0, and lists can be sliced,
511 concatenated and so on::
521 >>> a[:2] + ['bacon', 2*2]
522 ['spam', 'eggs', 'bacon', 4]
523 >>> 3*a[:3] + ['Boo!']
524 ['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boo!']
526 Unlike strings, which are *immutable*, it is possible to change individual
530 ['spam', 'eggs', 100, 1234]
533 ['spam', 'eggs', 123, 1234]
535 Assignment to slices is also possible, and this can even change the size of the
536 list or clear it entirely::
538 >>> # Replace some items:
547 ... a[1:1] = ['bletch', 'xyzzy']
549 [123, 'bletch', 'xyzzy', 1234]
550 >>> # Insert (a copy of) itself at the beginning
553 [123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234]
554 >>> # Clear the list: replace all items with an empty list
559 The built-in function :func:`len` also applies to lists::
561 >>> a = ['a', 'b', 'c', 'd']
565 It is possible to nest lists (create lists containing other lists), for
576 >>> p[1].append('xtra') # See section 5.1
578 [1, [2, 3, 'xtra'], 4]
582 Note that in the last example, ``p[1]`` and ``q`` really refer to the same
583 object! We'll come back to *object semantics* later.
588 First Steps Towards Programming
589 ===============================
591 Of course, we can use Python for more complicated tasks than adding two and two
592 together. For instance, we can write an initial sub-sequence of the *Fibonacci*
595 >>> # Fibonacci series:
596 ... # the sum of two elements defines the next
609 This example introduces several new features.
611 * The first line contains a *multiple assignment*: the variables ``a`` and ``b``
612 simultaneously get the new values 0 and 1. On the last line this is used again,
613 demonstrating that the expressions on the right-hand side are all evaluated
614 first before any of the assignments take place. The right-hand side expressions
615 are evaluated from the left to the right.
617 * The :keyword:`while` loop executes as long as the condition (here: ``b < 10``)
618 remains true. In Python, like in C, any non-zero integer value is true; zero is
619 false. The condition may also be a string or list value, in fact any sequence;
620 anything with a non-zero length is true, empty sequences are false. The test
621 used in the example is a simple comparison. The standard comparison operators
622 are written the same as in C: ``<`` (less than), ``>`` (greater than), ``==``
623 (equal to), ``<=`` (less than or equal to), ``>=`` (greater than or equal to)
624 and ``!=`` (not equal to).
626 * The *body* of the loop is *indented*: indentation is Python's way of grouping
627 statements. Python does not (yet!) provide an intelligent input line editing
628 facility, so you have to type a tab or space(s) for each indented line. In
629 practice you will prepare more complicated input for Python with a text editor;
630 most text editors have an auto-indent facility. When a compound statement is
631 entered interactively, it must be followed by a blank line to indicate
632 completion (since the parser cannot guess when you have typed the last line).
633 Note that each line within a basic block must be indented by the same amount.
635 * The :keyword:`print` statement writes the value of the expression(s) it is
636 given. It differs from just writing the expression you want to write (as we did
637 earlier in the calculator examples) in the way it handles multiple expressions
638 and strings. Strings are printed without quotes, and a space is inserted
639 between items, so you can format things nicely, like this::
642 >>> print 'The value of i is', i
643 The value of i is 65536
645 A trailing comma avoids the newline after the output::
652 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
654 Note that the interpreter inserts a newline before it prints the next prompt if
655 the last line was not completed.