blob: c138ce69eb3f1e588da6da920282ef79e996b34b [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001.. _tut-informal:
2
3**********************************
4An Informal Introduction to Python
5**********************************
6
7In the following examples, input and output are distinguished by the presence or
8absence of prompts (``>>>`` and ``...``): to repeat the example, you must type
9everything after the prompt, when the prompt appears; lines that do not begin
10with a prompt are output from the interpreter. Note that a secondary prompt on a
11line by itself in an example means you must type a blank line; this is used to
12end a multi-line command.
13
Georg Brandl8ec7f652007-08-15 14:28:01 +000014Many of the examples in this manual, even those entered at the interactive
15prompt, include comments. Comments in Python start with the hash character,
Georg Brandlb19be572007-12-29 10:57:00 +000016``#``, and extend to the end of the physical line. A comment may appear at
Georg Brandl8ec7f652007-08-15 14:28:01 +000017the start of a line or following whitespace or code, but not within a string
Georg Brandlb19be572007-12-29 10:57:00 +000018literal. A hash character within a string literal is just a hash character.
Georg Brandl8ec7f652007-08-15 14:28:01 +000019
20Some examples::
21
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."
26
27
28.. _tut-calculator:
29
30Using Python as a Calculator
31============================
32
33Let's try some simple Python commands. Start the interpreter and wait for the
34primary prompt, ``>>>``. (It shouldn't take long.)
35
36
37.. _tut-numbers:
38
39Numbers
40-------
41
42The interpreter acts as a simple calculator: you can type an expression at it
43and it will write the value. Expression syntax is straightforward: the
44operators ``+``, ``-``, ``*`` and ``/`` work just like in most other languages
45(for example, Pascal or C); parentheses can be used for grouping. For example::
46
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
61
62The equal sign (``'='``) is used to assign a value to a variable. Afterwards, no
63result is displayed before the next interactive prompt::
64
65 >>> width = 20
66 >>> height = 5*9
67 >>> width * height
68 900
69
70A value can be assigned to several variables simultaneously::
71
72 >>> x = y = z = 0 # Zero x, y and z
73 >>> x
74 0
75 >>> y
76 0
77 >>> z
78 0
79
80There is full support for floating point; operators with mixed type operands
81convert the integer operand to floating point::
82
83 >>> 3 * 3.75 / 1.5
84 7.5
85 >>> 7.0 / 2
86 3.5
87
88Complex numbers are also supported; imaginary numbers are written with a suffix
89of ``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.
91::
92
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)
103
104Complex numbers are always represented as two floating point numbers, the real
105and imaginary part. To extract these parts from a complex number *z*, use
106``z.real`` and ``z.imag``. ::
107
108 >>> a=1.5+0.5j
109 >>> a.real
110 1.5
111 >>> a.imag
112 0.5
113
114The 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
116correct way to convert a complex number to a real number. Use ``abs(z)`` to get
117its magnitude (as a float) or ``z.real`` to get its real part. ::
118
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 >>>
131
132In 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
134somewhat easier to continue calculations, for example::
135
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 >>>
145
146This variable should be treated as read-only by the user. Don't explicitly
147assign a value to it --- you would create an independent local variable with the
148same name masking the built-in variable with its magic behavior.
149
150
151.. _tut-strings:
152
153Strings
154-------
155
156Besides numbers, Python can also manipulate strings, which can be expressed in
157several ways. They can be enclosed in single quotes or double quotes::
158
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.'
171
172String literals can span multiple lines in several ways. Continuation lines can
173be used, with a backslash as the last character on the line indicating that the
174next line is a logical continuation of the line::
175
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."
180
181 print hello
182
183Note that newlines still need to be embedded in the string using ``\n``; the
184newline following the trailing backslash is discarded. This example would print
185the following::
186
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.
190
191If we make the string literal a "raw" string, however, the ``\n`` sequences are
192not converted to newlines, but the backslash at the end of the line, and the
193newline character in the source, are both included in the string as data. Thus,
194the example::
195
196 hello = r"This is a rather long string containing\n\
197 several lines of text much as you would do in C."
198
199 print hello
200
201would print::
202
203 This is a rather long string containing\n\
204 several lines of text much as you would do in C.
205
206Or, 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
208they will be included in the string. ::
209
210 print """
211 Usage: thingy [OPTIONS]
212 -h Display this usage message
213 -H hostname Hostname to connect to
214 """
215
216produces the following output::
217
218 Usage: thingy [OPTIONS]
219 -h Display this usage message
220 -H hostname Hostname to connect to
221
222The interpreter prints the result of string operations in the same way as they
223are typed for input: inside quotes, and with quotes and other funny characters
224escaped by backslashes, to show the precise value. The string is enclosed in
225double quotes if the string contains a single quote and no double quotes, else
226it's enclosed in single quotes. (The :keyword:`print` statement, described
227later, can be used to write strings without quotes or escapes.)
228
229Strings can be concatenated (glued together) with the ``+`` operator, and
230repeated with ``*``::
231
232 >>> word = 'Help' + 'A'
233 >>> word
234 'HelpA'
235 >>> '<' + word*5 + '>'
236 '<HelpAHelpAHelpAHelpAHelpA>'
237
238Two string literals next to each other are automatically concatenated; the first
239line above could also have been written ``word = 'Help' 'A'``; this only works
240with two literals, not with arbitrary string expressions::
241
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
251
252Strings can be subscripted (indexed); like in C, the first character of a string
253has subscript (index) 0. There is no separate character type; a character is
254simply a string of size one. Like in Icon, substrings can be specified with the
255*slice notation*: two indices separated by a colon. ::
256
257 >>> word[4]
258 'A'
259 >>> word[0:2]
260 'He'
261 >>> word[2:4]
262 'lp'
263
264Slice indices have useful defaults; an omitted first index defaults to zero, an
265omitted second index defaults to the size of the string being sliced. ::
266
267 >>> word[:2] # The first two characters
268 'He'
269 >>> word[2:] # Everything except the first two characters
270 'lpA'
271
272Unlike a C string, Python strings cannot be changed. Assigning to an indexed
273position in the string results in an error::
274
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
283
284However, creating a new string with the combined content is easy and efficient::
285
286 >>> 'x' + word[1:]
287 'xelpA'
288 >>> 'Splat' + word[4]
289 'SplatA'
290
291Here's a useful invariant of slice operations: ``s[:i] + s[i:]`` equals ``s``.
292::
293
294 >>> word[:2] + word[2:]
295 'HelpA'
296 >>> word[:3] + word[3:]
297 'HelpA'
298
299Degenerate slice indices are handled gracefully: an index that is too large is
300replaced by the string size, an upper bound smaller than the lower bound returns
301an empty string. ::
302
303 >>> word[1:100]
304 'elpA'
305 >>> word[10:]
306 ''
307 >>> word[2:1]
308 ''
309
310Indices may be negative numbers, to start counting from the right. For example::
311
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'
320
321But note that -0 is really the same as 0, so it does not count from the right!
322::
323
324 >>> word[-0] # (since -0 equals 0)
325 'H'
326
327Out-of-range negative slice indices are truncated, but don't try this for
328single-element (non-slice) indices::
329
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
336
337One 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.
339Then the right edge of the last character of a string of *n* characters has
340index *n*, for example::
341
342 +---+---+---+---+---+
343 | H | e | l | p | A |
344 +---+---+---+---+---+
345 0 1 2 3 4 5
346 -5 -4 -3 -2 -1
347
348The first row of numbers gives the position of the indices 0...5 in the string;
349the 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*,
351respectively.
352
353For non-negative indices, the length of a slice is the difference of the
354indices, if both are within bounds. For example, the length of ``word[1:3]`` is
3552.
356
357The built-in function :func:`len` returns the length of a string::
358
359 >>> s = 'supercalifragilisticexpialidocious'
360 >>> len(s)
361 34
362
363
364.. seealso::
365
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.
370
371 :ref:`string-methods`
372 Both strings and Unicode strings support a large number of methods for
373 basic transformations and searching.
374
Benjamin Petersonf9ef9882008-05-26 00:54:22 +0000375 :ref:`new-string-formatting`
376 Information about string formatting with :meth:`str.format` is described
377 here.
378
Georg Brandl8ec7f652007-08-15 14:28:01 +0000379 :ref:`string-formatting`
Benjamin Petersonf9ef9882008-05-26 00:54:22 +0000380 The old formatting operations invoked when strings and Unicode strings are
381 the left operand of the ``%`` operator are described in more detail here.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000382
383
384.. _tut-unicodestrings:
385
386Unicode Strings
387---------------
388
389.. sectionauthor:: Marc-Andre Lemburg <mal@lemburg.com>
390
391
392Starting with Python 2.0 a new data type for storing text data is available to
393the programmer: the Unicode object. It can be used to store and manipulate
394Unicode data (see http://www.unicode.org/) and integrates well with the existing
395string objects, providing auto-conversions where necessary.
396
397Unicode has the advantage of providing one ordinal for every character in every
398script used in modern and ancient texts. Previously, there were only 256
399possible ordinals for script characters. Texts were typically bound to a code
400page which mapped the ordinals to script characters. This lead to very much
401confusion especially with respect to internationalization (usually written as
402``i18n`` --- ``'i'`` + 18 characters + ``'n'``) of software. Unicode solves
403these problems by defining one code page for all scripts.
404
405Creating Unicode strings in Python is just as simple as creating normal
406strings::
407
408 >>> u'Hello World !'
409 u'Hello World !'
410
411The small ``'u'`` in front of the quote indicates that a Unicode string is
412supposed to be created. If you want to include special characters in the string,
413you can do so by using the Python *Unicode-Escape* encoding. The following
414example shows how::
415
416 >>> u'Hello\u0020World !'
417 u'Hello World !'
418
419The escape sequence ``\u0020`` indicates to insert the Unicode character with
420the ordinal value 0x0020 (the space character) at the given position.
421
422Other characters are interpreted by using their respective ordinal values
423directly as Unicode ordinals. If you have literal strings in the standard
424Latin-1 encoding that is used in many Western countries, you will find it
425convenient that the lower 256 characters of Unicode are the same as the 256
426characters of Latin-1.
427
428For experts, there is also a raw mode just like the one for normal strings. You
429have to prefix the opening quote with 'ur' to have Python use the
430*Raw-Unicode-Escape* encoding. It will only apply the above ``\uXXXX``
431conversion if there is an uneven number of backslashes in front of the small
432'u'. ::
433
434 >>> ur'Hello\u0020World !'
435 u'Hello World !'
436 >>> ur'Hello\\u0020World !'
437 u'Hello\\\\u0020World !'
438
439The raw mode is most useful when you have to enter lots of backslashes, as can
440be necessary in regular expressions.
441
442Apart from these standard encodings, Python provides a whole set of other ways
443of creating Unicode strings on the basis of a known encoding.
444
445.. index:: builtin: unicode
446
447The built-in function :func:`unicode` provides access to all registered Unicode
448codecs (COders and DECoders). Some of the more well known encodings which these
449codecs can convert are *Latin-1*, *ASCII*, *UTF-8*, and *UTF-16*. The latter two
450are variable-length encodings that store each Unicode character in one or more
451bytes. The default encoding is normally set to ASCII, which passes through
452characters in the range 0 to 127 and rejects any other characters with an error.
453When a Unicode string is printed, written to a file, or converted with
454:func:`str`, conversion takes place using this default encoding. ::
455
456 >>> u"abc"
457 u'abc'
458 >>> str(u"abc")
459 'abc'
460 >>> u"äöü"
461 u'\xe4\xf6\xfc'
462 >>> str(u"äöü")
463 Traceback (most recent call last):
464 File "<stdin>", line 1, in ?
465 UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)
466
467To convert a Unicode string into an 8-bit string using a specific encoding,
468Unicode objects provide an :func:`encode` method that takes one argument, the
469name of the encoding. Lowercase names for encodings are preferred. ::
470
471 >>> u"äöü".encode('utf-8')
472 '\xc3\xa4\xc3\xb6\xc3\xbc'
473
474If you have data in a specific encoding and want to produce a corresponding
475Unicode string from it, you can use the :func:`unicode` function with the
476encoding name as the second argument. ::
477
478 >>> unicode('\xc3\xa4\xc3\xb6\xc3\xbc', 'utf-8')
479 u'\xe4\xf6\xfc'
480
481
482.. _tut-lists:
483
484Lists
485-----
486
487Python knows a number of *compound* data types, used to group together other
488values. The most versatile is the *list*, which can be written as a list of
489comma-separated values (items) between square brackets. List items need not all
490have the same type. ::
491
492 >>> a = ['spam', 'eggs', 100, 1234]
493 >>> a
494 ['spam', 'eggs', 100, 1234]
495
496Like string indices, list indices start at 0, and lists can be sliced,
497concatenated and so on::
498
499 >>> a[0]
500 'spam'
501 >>> a[3]
502 1234
503 >>> a[-2]
504 100
505 >>> a[1:-1]
506 ['eggs', 100]
507 >>> a[:2] + ['bacon', 2*2]
508 ['spam', 'eggs', 'bacon', 4]
509 >>> 3*a[:3] + ['Boo!']
510 ['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boo!']
511
512Unlike strings, which are *immutable*, it is possible to change individual
513elements of a list::
514
515 >>> a
516 ['spam', 'eggs', 100, 1234]
517 >>> a[2] = a[2] + 23
518 >>> a
519 ['spam', 'eggs', 123, 1234]
520
521Assignment to slices is also possible, and this can even change the size of the
522list or clear it entirely::
523
524 >>> # Replace some items:
525 ... a[0:2] = [1, 12]
526 >>> a
527 [1, 12, 123, 1234]
528 >>> # Remove some:
529 ... a[0:2] = []
530 >>> a
531 [123, 1234]
532 >>> # Insert some:
533 ... a[1:1] = ['bletch', 'xyzzy']
534 >>> a
535 [123, 'bletch', 'xyzzy', 1234]
536 >>> # Insert (a copy of) itself at the beginning
537 >>> a[:0] = a
538 >>> a
539 [123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234]
540 >>> # Clear the list: replace all items with an empty list
541 >>> a[:] = []
542 >>> a
543 []
544
545The built-in function :func:`len` also applies to lists::
546
Georg Brandl87426cb2007-11-09 13:08:48 +0000547 >>> a = ['a', 'b', 'c', 'd']
Georg Brandl8ec7f652007-08-15 14:28:01 +0000548 >>> len(a)
Georg Brandl87426cb2007-11-09 13:08:48 +0000549 4
Georg Brandl8ec7f652007-08-15 14:28:01 +0000550
551It is possible to nest lists (create lists containing other lists), for
552example::
553
554 >>> q = [2, 3]
555 >>> p = [1, q, 4]
556 >>> len(p)
557 3
558 >>> p[1]
559 [2, 3]
560 >>> p[1][0]
561 2
562 >>> p[1].append('xtra') # See section 5.1
563 >>> p
564 [1, [2, 3, 'xtra'], 4]
565 >>> q
566 [2, 3, 'xtra']
567
568Note that in the last example, ``p[1]`` and ``q`` really refer to the same
569object! We'll come back to *object semantics* later.
570
571
572.. _tut-firststeps:
573
574First Steps Towards Programming
575===============================
576
577Of course, we can use Python for more complicated tasks than adding two and two
578together. For instance, we can write an initial sub-sequence of the *Fibonacci*
579series as follows::
580
581 >>> # Fibonacci series:
582 ... # the sum of two elements defines the next
583 ... a, b = 0, 1
584 >>> while b < 10:
Georg Brandl35f88612008-01-06 22:05:40 +0000585 ... print b
586 ... a, b = b, a+b
Georg Brandl8ec7f652007-08-15 14:28:01 +0000587 ...
588 1
589 1
590 2
591 3
592 5
593 8
594
595This example introduces several new features.
596
597* The first line contains a *multiple assignment*: the variables ``a`` and ``b``
598 simultaneously get the new values 0 and 1. On the last line this is used again,
599 demonstrating that the expressions on the right-hand side are all evaluated
600 first before any of the assignments take place. The right-hand side expressions
601 are evaluated from the left to the right.
602
603* The :keyword:`while` loop executes as long as the condition (here: ``b < 10``)
604 remains true. In Python, like in C, any non-zero integer value is true; zero is
605 false. The condition may also be a string or list value, in fact any sequence;
606 anything with a non-zero length is true, empty sequences are false. The test
607 used in the example is a simple comparison. The standard comparison operators
608 are written the same as in C: ``<`` (less than), ``>`` (greater than), ``==``
609 (equal to), ``<=`` (less than or equal to), ``>=`` (greater than or equal to)
610 and ``!=`` (not equal to).
611
612* The *body* of the loop is *indented*: indentation is Python's way of grouping
613 statements. Python does not (yet!) provide an intelligent input line editing
614 facility, so you have to type a tab or space(s) for each indented line. In
615 practice you will prepare more complicated input for Python with a text editor;
616 most text editors have an auto-indent facility. When a compound statement is
617 entered interactively, it must be followed by a blank line to indicate
618 completion (since the parser cannot guess when you have typed the last line).
619 Note that each line within a basic block must be indented by the same amount.
620
621* The :keyword:`print` statement writes the value of the expression(s) it is
622 given. It differs from just writing the expression you want to write (as we did
623 earlier in the calculator examples) in the way it handles multiple expressions
624 and strings. Strings are printed without quotes, and a space is inserted
625 between items, so you can format things nicely, like this::
626
627 >>> i = 256*256
628 >>> print 'The value of i is', i
629 The value of i is 65536
630
631 A trailing comma avoids the newline after the output::
632
633 >>> a, b = 0, 1
634 >>> while b < 1000:
635 ... print b,
636 ... a, b = b, a+b
637 ...
638 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
639
640 Note that the interpreter inserts a newline before it prints the next prompt if
641 the last line was not completed.