Fixed: #2914 (RFE for UTC support in TimedRotatingFileHandler) and #2929 (wrong filen...
[python.git] / Doc / tutorial / introduction.rst
blob5e027a061101082242ec62b6ae5d6c2e5cc1f1cc
1 .. _tut-informal:
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
17 the 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.
20 Some examples::
22    # this is the first comment
23    SPAM = 1                 # and this is the second comment
24                             # ... and now a third!
25    STRING = "# This is not a comment."
28 .. _tut-calculator:
30 Using Python as a Calculator
31 ============================
33 Let's try some simple Python commands.  Start the interpreter and wait for the
34 primary prompt, ``>>>``.  (It shouldn't take long.)
37 .. _tut-numbers:
39 Numbers
40 -------
42 The interpreter acts as a simple calculator: you can type an expression at it
43 and it will write the value.  Expression syntax is straightforward: the
44 operators ``+``, ``-``, ``*`` and ``/`` work just like in most other languages
45 (for example, Pascal or C); parentheses can be used for grouping.  For example::
47    >>> 2+2
48    4
49    >>> # This is a comment
50    ... 2+2
51    4
52    >>> 2+2  # and a comment on the same line as code
53    4
54    >>> (50-5*6)/4
55    5
56    >>> # Integer division returns the floor:
57    ... 7/3
58    2
59    >>> 7/-3
60    -3
62 The equal sign (``'='``) is used to assign a value to a variable. Afterwards, no
63 result is displayed before the next interactive prompt::
65    >>> width = 20
66    >>> height = 5*9
67    >>> width * height
68    900
70 A value can be assigned to several variables simultaneously::
72    >>> x = y = z = 0  # Zero x, y and z
73    >>> x
74    0
75    >>> y
76    0
77    >>> z
78    0
80 There is full support for floating point; operators with mixed type operands
81 convert the integer operand to floating point::
83    >>> 3 * 3.75 / 1.5
84    7.5
85    >>> 7.0 / 2
86    3.5
88 Complex numbers are also supported; imaginary numbers are written with a suffix
89 of ``j`` or ``J``.  Complex numbers with a nonzero real component are written as
90 ``(real+imagj)``, or can be created with the ``complex(real, imag)`` function.
93    >>> 1j * 1J
94    (-1+0j)
95    >>> 1j * complex(0,1)
96    (-1+0j)
97    >>> 3+1j*3
98    (3+3j)
99    >>> (3+1j)*3
100    (9+3j)
101    >>> (1+2j)/(1+1j)
102    (1.5+0.5j)
104 Complex numbers are always represented as two floating point numbers, the real
105 and imaginary part.  To extract these parts from a complex number *z*, use
106 ``z.real`` and ``z.imag``.   ::
108    >>> a=1.5+0.5j
109    >>> a.real
110    1.5
111    >>> a.imag
112    0.5
114 The conversion functions to floating point and integer (:func:`float`,
115 :func:`int` and :func:`long`) don't work for complex numbers --- there is no one
116 correct way to convert a complex number to a real number.  Use ``abs(z)`` to get
117 its magnitude (as a float) or ``z.real`` to get its real part. ::
119    >>> a=3.0+4.0j
120    >>> float(a)
121    Traceback (most recent call last):
122      File "<stdin>", line 1, in ?
123    TypeError: can't convert complex to float; use abs(z)
124    >>> a.real
125    3.0
126    >>> a.imag
127    4.0
128    >>> abs(a)  # sqrt(a.real**2 + a.imag**2)
129    5.0
130    >>>
132 In interactive mode, the last printed expression is assigned to the variable
133 ``_``.  This means that when you are using Python as a desk calculator, it is
134 somewhat easier to continue calculations, for example::
136    >>> tax = 12.5 / 100
137    >>> price = 100.50
138    >>> price * tax
139    12.5625
140    >>> price + _
141    113.0625
142    >>> round(_, 2)
143    113.06
144    >>>
146 This variable should be treated as read-only by the user.  Don't explicitly
147 assign a value to it --- you would create an independent local variable with the
148 same name masking the built-in variable with its magic behavior.
151 .. _tut-strings:
153 Strings
154 -------
156 Besides numbers, Python can also manipulate strings, which can be expressed in
157 several ways.  They can be enclosed in single quotes or double quotes::
159    >>> 'spam eggs'
160    'spam eggs'
161    >>> 'doesn\'t'
162    "doesn't"
163    >>> "doesn't"
164    "doesn't"
165    >>> '"Yes," he said.'
166    '"Yes," he said.'
167    >>> "\"Yes,\" he said."
168    '"Yes," he said.'
169    >>> '"Isn\'t," she said.'
170    '"Isn\'t," she said.'
172 String literals can span multiple lines in several ways.  Continuation lines can
173 be used, with a backslash as the last character on the line indicating that the
174 next line is a logical continuation of the line::
176    hello = "This is a rather long string containing\n\
177    several lines of text just as you would do in C.\n\
178        Note that whitespace at the beginning of the line is\
179     significant."
181    print hello
183 Note that newlines still need to be embedded in the string using ``\n``; the
184 newline following the trailing backslash is discarded.  This example would print
185 the following::
187    This is a rather long string containing
188    several lines of text just as you would do in C.
189        Note that whitespace at the beginning of the line is significant.
191 If we make the string literal a "raw" string, however, the ``\n`` sequences are
192 not converted to newlines, but the backslash at the end of the line, and the
193 newline character in the source, are both included in the string as data.  Thus,
194 the example::
196    hello = r"This is a rather long string containing\n\
197    several lines of text much as you would do in C."
199    print hello
201 would print::
203    This is a rather long string containing\n\
204    several lines of text much as you would do in C.
206 Or, strings can be surrounded in a pair of matching triple-quotes: ``"""`` or
207 ``'''``.  End of lines do not need to be escaped when using triple-quotes, but
208 they will be included in the string. ::
210    print """
211    Usage: thingy [OPTIONS] 
212         -h                        Display this usage message
213         -H hostname               Hostname to connect to
214    """
216 produces the following output::
218    Usage: thingy [OPTIONS] 
219         -h                        Display this usage message
220         -H hostname               Hostname to connect to
222 The interpreter prints the result of string operations in the same way as they
223 are typed for input: inside quotes, and with quotes and other funny characters
224 escaped by backslashes, to show the precise value.  The string is enclosed in
225 double quotes if the string contains a single quote and no double quotes, else
226 it's enclosed in single quotes.  (The :keyword:`print` statement, described
227 later, can be used to write strings without quotes or escapes.)
229 Strings can be concatenated (glued together) with the ``+`` operator, and
230 repeated with ``*``::
232    >>> word = 'Help' + 'A'
233    >>> word
234    'HelpA'
235    >>> '<' + word*5 + '>'
236    '<HelpAHelpAHelpAHelpAHelpA>'
238 Two string literals next to each other are automatically concatenated; the first
239 line above could also have been written ``word = 'Help' 'A'``; this only works
240 with two literals, not with arbitrary string expressions::
242    >>> 'str' 'ing'                   #  <-  This is ok
243    'string'
244    >>> 'str'.strip() + 'ing'   #  <-  This is ok
245    'string'
246    >>> 'str'.strip() 'ing'     #  <-  This is invalid
247      File "<stdin>", line 1, in ?
248        'str'.strip() 'ing'
249                          ^
250    SyntaxError: invalid syntax
252 Strings can be subscripted (indexed); like in C, the first character of a string
253 has subscript (index) 0.  There is no separate character type; a character is
254 simply a string of size one.  Like in Icon, substrings can be specified with the
255 *slice notation*: two indices separated by a colon. ::
257    >>> word[4]
258    'A'
259    >>> word[0:2]
260    'He'
261    >>> word[2:4]
262    'lp'
264 Slice indices have useful defaults; an omitted first index defaults to zero, an
265 omitted second index defaults to the size of the string being sliced. ::
267    >>> word[:2]    # The first two characters
268    'He'
269    >>> word[2:]    # Everything except the first two characters
270    'lpA'
272 Unlike a C string, Python strings cannot be changed.  Assigning to an  indexed
273 position in the string results in an error::
275    >>> word[0] = 'x'
276    Traceback (most recent call last):
277      File "<stdin>", line 1, in ?
278    TypeError: object doesn't support item assignment
279    >>> word[:1] = 'Splat'
280    Traceback (most recent call last):
281      File "<stdin>", line 1, in ?
282    TypeError: object doesn't support slice assignment
284 However, creating a new string with the combined content is easy and efficient::
286    >>> 'x' + word[1:]
287    'xelpA'
288    >>> 'Splat' + word[4]
289    'SplatA'
291 Here's a useful invariant of slice operations: ``s[:i] + s[i:]`` equals ``s``.
294    >>> word[:2] + word[2:]
295    'HelpA'
296    >>> word[:3] + word[3:]
297    'HelpA'
299 Degenerate slice indices are handled gracefully: an index that is too large is
300 replaced by the string size, an upper bound smaller than the lower bound returns
301 an empty string. ::
303    >>> word[1:100]
304    'elpA'
305    >>> word[10:]
306    ''
307    >>> word[2:1]
308    ''
310 Indices may be negative numbers, to start counting from the right. For example::
312    >>> word[-1]     # The last character
313    'A'
314    >>> word[-2]     # The last-but-one character
315    'p'
316    >>> word[-2:]    # The last two characters
317    'pA'
318    >>> word[:-2]    # Everything except the last two characters
319    'Hel'
321 But note that -0 is really the same as 0, so it does not count from the right!
324    >>> word[-0]     # (since -0 equals 0)
325    'H'
327 Out-of-range negative slice indices are truncated, but don't try this for
328 single-element (non-slice) indices::
330    >>> word[-100:]
331    'HelpA'
332    >>> word[-10]    # error
333    Traceback (most recent call last):
334      File "<stdin>", line 1, in ?
335    IndexError: string index out of range
337 One way to remember how slices work is to think of the indices as pointing
338 *between* characters, with the left edge of the first character numbered 0.
339 Then the right edge of the last character of a string of *n* characters has
340 index *n*, for example::
342     +---+---+---+---+---+ 
343     | H | e | l | p | A |
344     +---+---+---+---+---+ 
345     0   1   2   3   4   5 
346    -5  -4  -3  -2  -1
348 The first row of numbers gives the position of the indices 0...5 in the string;
349 the second row gives the corresponding negative indices. The slice from *i* to
350 *j* consists of all characters between the edges labeled *i* and *j*,
351 respectively.
353 For non-negative indices, the length of a slice is the difference of the
354 indices, if both are within bounds.  For example, the length of ``word[1:3]`` is
357 The built-in function :func:`len` returns the length of a string::
359    >>> s = 'supercalifragilisticexpialidocious'
360    >>> len(s)
361    34
364 .. seealso::
366    :ref:`typesseq`
367       Strings, and the Unicode strings described in the next section, are
368       examples of *sequence types*, and support the common operations supported
369       by such types.
371    :ref:`string-methods`
372       Both strings and Unicode strings support a large number of methods for
373       basic transformations and searching.
375    :ref:`string-formatting`
376       The formatting operations invoked when strings and Unicode strings are the
377       left operand of the ``%`` operator are described in more detail here.
380 .. _tut-unicodestrings:
382 Unicode Strings
383 ---------------
385 .. sectionauthor:: Marc-Andre Lemburg <mal@lemburg.com>
388 Starting with Python 2.0 a new data type for storing text data is available to
389 the programmer: the Unicode object. It can be used to store and manipulate
390 Unicode data (see http://www.unicode.org/) and integrates well with the existing
391 string objects, providing auto-conversions where necessary.
393 Unicode has the advantage of providing one ordinal for every character in every
394 script used in modern and ancient texts. Previously, there were only 256
395 possible ordinals for script characters. Texts were typically bound to a code
396 page which mapped the ordinals to script characters. This lead to very much
397 confusion especially with respect to internationalization (usually written as
398 ``i18n`` --- ``'i'`` + 18 characters + ``'n'``) of software.  Unicode solves
399 these problems by defining one code page for all scripts.
401 Creating Unicode strings in Python is just as simple as creating normal
402 strings::
404    >>> u'Hello World !'
405    u'Hello World !'
407 The small ``'u'`` in front of the quote indicates that a Unicode string is
408 supposed to be created. If you want to include special characters in the string,
409 you can do so by using the Python *Unicode-Escape* encoding. The following
410 example shows how::
412    >>> u'Hello\u0020World !'
413    u'Hello World !'
415 The escape sequence ``\u0020`` indicates to insert the Unicode character with
416 the ordinal value 0x0020 (the space character) at the given position.
418 Other characters are interpreted by using their respective ordinal values
419 directly as Unicode ordinals.  If you have literal strings in the standard
420 Latin-1 encoding that is used in many Western countries, you will find it
421 convenient that the lower 256 characters of Unicode are the same as the 256
422 characters of Latin-1.
424 For experts, there is also a raw mode just like the one for normal strings. You
425 have to prefix the opening quote with 'ur' to have Python use the
426 *Raw-Unicode-Escape* encoding. It will only apply the above ``\uXXXX``
427 conversion if there is an uneven number of backslashes in front of the small
428 'u'. ::
430    >>> ur'Hello\u0020World !'
431    u'Hello World !'
432    >>> ur'Hello\\u0020World !'
433    u'Hello\\\\u0020World !'
435 The raw mode is most useful when you have to enter lots of backslashes, as can
436 be necessary in regular expressions.
438 Apart from these standard encodings, Python provides a whole set of other ways
439 of creating Unicode strings on the basis of a known encoding.
441 .. index:: builtin: unicode
443 The built-in function :func:`unicode` provides access to all registered Unicode
444 codecs (COders and DECoders). Some of the more well known encodings which these
445 codecs can convert are *Latin-1*, *ASCII*, *UTF-8*, and *UTF-16*. The latter two
446 are variable-length encodings that store each Unicode character in one or more
447 bytes. The default encoding is normally set to ASCII, which passes through
448 characters in the range 0 to 127 and rejects any other characters with an error.
449 When a Unicode string is printed, written to a file, or converted with
450 :func:`str`, conversion takes place using this default encoding. ::
452    >>> u"abc"
453    u'abc'
454    >>> str(u"abc")
455    'abc'
456    >>> u"äöü"
457    u'\xe4\xf6\xfc'
458    >>> str(u"äöü")
459    Traceback (most recent call last):
460      File "<stdin>", line 1, in ?
461    UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)
463 To convert a Unicode string into an 8-bit string using a specific encoding,
464 Unicode objects provide an :func:`encode` method that takes one argument, the
465 name of the encoding.  Lowercase names for encodings are preferred. ::
467    >>> u"äöü".encode('utf-8')
468    '\xc3\xa4\xc3\xb6\xc3\xbc'
470 If you have data in a specific encoding and want to produce a corresponding
471 Unicode string from it, you can use the :func:`unicode` function with the
472 encoding name as the second argument. ::
474    >>> unicode('\xc3\xa4\xc3\xb6\xc3\xbc', 'utf-8')
475    u'\xe4\xf6\xfc'
478 .. _tut-lists:
480 Lists
481 -----
483 Python knows a number of *compound* data types, used to group together other
484 values.  The most versatile is the *list*, which can be written as a list of
485 comma-separated values (items) between square brackets.  List items need not all
486 have the same type. ::
488    >>> a = ['spam', 'eggs', 100, 1234]
489    >>> a
490    ['spam', 'eggs', 100, 1234]
492 Like string indices, list indices start at 0, and lists can be sliced,
493 concatenated and so on::
495    >>> a[0]
496    'spam'
497    >>> a[3]
498    1234
499    >>> a[-2]
500    100
501    >>> a[1:-1]
502    ['eggs', 100]
503    >>> a[:2] + ['bacon', 2*2]
504    ['spam', 'eggs', 'bacon', 4]
505    >>> 3*a[:3] + ['Boo!']
506    ['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boo!']
508 Unlike strings, which are *immutable*, it is possible to change individual
509 elements of a list::
511    >>> a
512    ['spam', 'eggs', 100, 1234]
513    >>> a[2] = a[2] + 23
514    >>> a
515    ['spam', 'eggs', 123, 1234]
517 Assignment to slices is also possible, and this can even change the size of the
518 list or clear it entirely::
520    >>> # Replace some items:
521    ... a[0:2] = [1, 12]
522    >>> a
523    [1, 12, 123, 1234]
524    >>> # Remove some:
525    ... a[0:2] = []
526    >>> a
527    [123, 1234]
528    >>> # Insert some:
529    ... a[1:1] = ['bletch', 'xyzzy']
530    >>> a
531    [123, 'bletch', 'xyzzy', 1234]
532    >>> # Insert (a copy of) itself at the beginning
533    >>> a[:0] = a
534    >>> a
535    [123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234]
536    >>> # Clear the list: replace all items with an empty list
537    >>> a[:] = []
538    >>> a
539    []
541 The built-in function :func:`len` also applies to lists::
543    >>> a = ['a', 'b', 'c', 'd']
544    >>> len(a)
545    4
547 It is possible to nest lists (create lists containing other lists), for
548 example::
550    >>> q = [2, 3]
551    >>> p = [1, q, 4]
552    >>> len(p)
553    3
554    >>> p[1]
555    [2, 3]
556    >>> p[1][0]
557    2
558    >>> p[1].append('xtra')     # See section 5.1
559    >>> p
560    [1, [2, 3, 'xtra'], 4]
561    >>> q
562    [2, 3, 'xtra']
564 Note that in the last example, ``p[1]`` and ``q`` really refer to the same
565 object!  We'll come back to *object semantics* later.
568 .. _tut-firststeps:
570 First Steps Towards Programming
571 ===============================
573 Of course, we can use Python for more complicated tasks than adding two and two
574 together.  For instance, we can write an initial sub-sequence of the *Fibonacci*
575 series as follows::
577    >>> # Fibonacci series:
578    ... # the sum of two elements defines the next
579    ... a, b = 0, 1
580    >>> while b < 10:
581    ...     print b
582    ...     a, b = b, a+b
583    ... 
584    1
585    1
586    2
587    3
588    5
589    8
591 This example introduces several new features.
593 * The first line contains a *multiple assignment*: the variables ``a`` and ``b``
594   simultaneously get the new values 0 and 1.  On the last line this is used again,
595   demonstrating that the expressions on the right-hand side are all evaluated
596   first before any of the assignments take place.  The right-hand side expressions
597   are evaluated  from the left to the right.
599 * The :keyword:`while` loop executes as long as the condition (here: ``b < 10``)
600   remains true.  In Python, like in C, any non-zero integer value is true; zero is
601   false.  The condition may also be a string or list value, in fact any sequence;
602   anything with a non-zero length is true, empty sequences are false.  The test
603   used in the example is a simple comparison.  The standard comparison operators
604   are written the same as in C: ``<`` (less than), ``>`` (greater than), ``==``
605   (equal to), ``<=`` (less than or equal to), ``>=`` (greater than or equal to)
606   and ``!=`` (not equal to).
608 * The *body* of the loop is *indented*: indentation is Python's way of grouping
609   statements.  Python does not (yet!) provide an intelligent input line editing
610   facility, so you have to type a tab or space(s) for each indented line.  In
611   practice you will prepare more complicated input for Python with a text editor;
612   most text editors have an auto-indent facility.  When a compound statement is
613   entered interactively, it must be followed by a blank line to indicate
614   completion (since the parser cannot guess when you have typed the last line).
615   Note that each line within a basic block must be indented by the same amount.
617 * The :keyword:`print` statement writes the value of the expression(s) it is
618   given.  It differs from just writing the expression you want to write (as we did
619   earlier in the calculator examples) in the way it handles multiple expressions
620   and strings.  Strings are printed without quotes, and a space is inserted
621   between items, so you can format things nicely, like this::
623      >>> i = 256*256
624      >>> print 'The value of i is', i
625      The value of i is 65536
627   A trailing comma avoids the newline after the output::
629      >>> a, b = 0, 1
630      >>> while b < 1000:
631      ...     print b,
632      ...     a, b = b, a+b
633      ... 
634      1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
636   Note that the interpreter inserts a newline before it prints the next prompt if
637   the last line was not completed.