Issue #7042: Use a better mechanism for testing timers in test_signal.
[python.git] / Doc / tutorial / introduction.rst
blob1d67ed3df022cc93918edef56a6efee920f4de17
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 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.
22 Some 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."
30 .. _tut-calculator:
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.)
39 .. _tut-numbers:
41 Numbers
42 -------
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::
49    >>> 2+2
50    4
51    >>> # This is a comment
52    ... 2+2
53    4
54    >>> 2+2  # and a comment on the same line as code
55    4
56    >>> (50-5*6)/4
57    5
58    >>> # Integer division returns the floor:
59    ... 7/3
60    2
61    >>> 7/-3
62    -3
64 The equal sign (``'='``) is used to assign a value to a variable. Afterwards, no
65 result is displayed before the next interactive prompt::
67    >>> width = 20
68    >>> height = 5*9
69    >>> width * height
70    900
72 A value can be assigned to several variables simultaneously::
74    >>> x = y = z = 0  # Zero x, y and z
75    >>> x
76    0
77    >>> y
78    0
79    >>> z
80    0
82 Variables must be "defined" (assigned a value) before they can be used, or an
83 error will occur::
85    >>> # try to access an undefined variable
86    ... n
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::
94    >>> 3 * 3.75 / 1.5
95    7.5
96    >>> 7.0 / 2
97    3.5
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.
104    >>> 1j * 1J
105    (-1+0j)
106    >>> 1j * complex(0,1)
107    (-1+0j)
108    >>> 3+1j*3
109    (3+3j)
110    >>> (3+1j)*3
111    (9+3j)
112    >>> (1+2j)/(1+1j)
113    (1.5+0.5j)
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``.   ::
119    >>> a=1.5+0.5j
120    >>> a.real
121    1.5
122    >>> a.imag
123    0.5
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. ::
130    >>> a=3.0+4.0j
131    >>> float(a)
132    Traceback (most recent call last):
133      File "<stdin>", line 1, in ?
134    TypeError: can't convert complex to float; use abs(z)
135    >>> a.real
136    3.0
137    >>> a.imag
138    4.0
139    >>> abs(a)  # sqrt(a.real**2 + a.imag**2)
140    5.0
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::
146    >>> tax = 12.5 / 100
147    >>> price = 100.50
148    >>> price * tax
149    12.5625
150    >>> price + _
151    113.0625
152    >>> round(_, 2)
153    113.06
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.
160 .. _tut-strings:
162 Strings
163 -------
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::
168    >>> 'spam eggs'
169    'spam eggs'
170    >>> 'doesn\'t'
171    "doesn't"
172    >>> "doesn't"
173    "doesn't"
174    >>> '"Yes," he said.'
175    '"Yes," he said.'
176    >>> "\"Yes,\" he said."
177    '"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\
188     significant."
190    print hello
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
194 the following:
196 .. code-block:: text
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. ::
206    print """
207    Usage: thingy [OPTIONS]
208         -h                        Display this usage message
209         -H hostname               Hostname to connect to
210    """
212 produces the following output:
214 .. code-block:: text
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."
227    print hello
229 would print:
231 .. code-block:: text
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'
247    >>> word
248    'HelpA'
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
257    'string'
258    >>> 'str'.strip() + 'ing'   #  <-  This is ok
259    'string'
260    >>> 'str'.strip() 'ing'     #  <-  This is invalid
261      File "<stdin>", line 1, in ?
262        'str'.strip() 'ing'
263                          ^
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. ::
271    >>> word[4]
272    'A'
273    >>> word[0:2]
274    'He'
275    >>> word[2:4]
276    'lp'
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
282    'He'
283    >>> word[2:]    # Everything except the first two characters
284    'lpA'
286 Unlike a C string, Python strings cannot be changed.  Assigning to an indexed
287 position in the string results in an error::
289    >>> word[0] = 'x'
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::
300    >>> 'x' + word[1:]
301    'xelpA'
302    >>> 'Splat' + word[4]
303    'SplatA'
305 Here's a useful invariant of slice operations: ``s[:i] + s[i:]`` equals ``s``.
308    >>> word[:2] + word[2:]
309    'HelpA'
310    >>> word[:3] + word[3:]
311    'HelpA'
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
315 an empty string. ::
317    >>> word[1:100]
318    'elpA'
319    >>> word[10:]
320    ''
321    >>> word[2:1]
322    ''
324 Indices may be negative numbers, to start counting from the right. For example::
326    >>> word[-1]     # The last character
327    'A'
328    >>> word[-2]     # The last-but-one character
329    'p'
330    >>> word[-2:]    # The last two characters
331    'pA'
332    >>> word[:-2]    # Everything except the last two characters
333    'Hel'
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)
339    'H'
341 Out-of-range negative slice indices are truncated, but don't try this for
342 single-element (non-slice) indices::
344    >>> word[-100:]
345    'HelpA'
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     +---+---+---+---+---+
359     0   1   2   3   4   5
360    -5  -4  -3  -2  -1
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*,
365 respectively.
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'
374    >>> len(s)
375    34
378 .. seealso::
380    :ref:`typesseq`
381       Strings, and the Unicode strings described in the next section, are
382       examples of *sequence types*, and support the common operations supported
383       by such types.
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
391       here.
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:
400 Unicode Strings
401 ---------------
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
420 strings::
422    >>> u'Hello World !'
423    u'Hello World !'
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
428 example shows how::
430    >>> u'Hello\u0020World !'
431    u'Hello World !'
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
446 'u'. ::
448    >>> ur'Hello\u0020World !'
449    u'Hello World !'
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. ::
470    >>> u"abc"
471    u'abc'
472    >>> str(u"abc")
473    'abc'
474    >>> u"äöü"
475    u'\xe4\xf6\xfc'
476    >>> str(u"äöü")
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')
493    u'\xe4\xf6\xfc'
496 .. _tut-lists:
498 Lists
499 -----
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]
507    >>> a
508    ['spam', 'eggs', 100, 1234]
510 Like string indices, list indices start at 0, and lists can be sliced,
511 concatenated and so on::
513    >>> a[0]
514    'spam'
515    >>> a[3]
516    1234
517    >>> a[-2]
518    100
519    >>> a[1:-1]
520    ['eggs', 100]
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
527 elements of a list::
529    >>> a
530    ['spam', 'eggs', 100, 1234]
531    >>> a[2] = a[2] + 23
532    >>> a
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:
539    ... a[0:2] = [1, 12]
540    >>> a
541    [1, 12, 123, 1234]
542    >>> # Remove some:
543    ... a[0:2] = []
544    >>> a
545    [123, 1234]
546    >>> # Insert some:
547    ... a[1:1] = ['bletch', 'xyzzy']
548    >>> a
549    [123, 'bletch', 'xyzzy', 1234]
550    >>> # Insert (a copy of) itself at the beginning
551    >>> a[:0] = a
552    >>> a
553    [123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234]
554    >>> # Clear the list: replace all items with an empty list
555    >>> a[:] = []
556    >>> a
557    []
559 The built-in function :func:`len` also applies to lists::
561    >>> a = ['a', 'b', 'c', 'd']
562    >>> len(a)
563    4
565 It is possible to nest lists (create lists containing other lists), for
566 example::
568    >>> q = [2, 3]
569    >>> p = [1, q, 4]
570    >>> len(p)
571    3
572    >>> p[1]
573    [2, 3]
574    >>> p[1][0]
575    2
576    >>> p[1].append('xtra')     # See section 5.1
577    >>> p
578    [1, [2, 3, 'xtra'], 4]
579    >>> q
580    [2, 3, 'xtra']
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.
586 .. _tut-firststeps:
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*
593 series as follows::
595    >>> # Fibonacci series:
596    ... # the sum of two elements defines the next
597    ... a, b = 0, 1
598    >>> while b < 10:
599    ...     print b
600    ...     a, b = b, a+b
601    ...
602    1
603    1
604    2
605    3
606    5
607    8
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::
641      >>> i = 256*256
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::
647      >>> a, b = 0, 1
648      >>> while b < 1000:
649      ...     print b,
650      ...     a, b = b, a+b
651      ...
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.