blob: 5e027a061101082242ec62b6ae5d6c2e5cc1f1cc [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
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.
378
379
380.. _tut-unicodestrings:
381
382Unicode Strings
383---------------
384
385.. sectionauthor:: Marc-Andre Lemburg <mal@lemburg.com>
386
387
388Starting with Python 2.0 a new data type for storing text data is available to
389the programmer: the Unicode object. It can be used to store and manipulate
390Unicode data (see http://www.unicode.org/) and integrates well with the existing
391string objects, providing auto-conversions where necessary.
392
393Unicode has the advantage of providing one ordinal for every character in every
394script used in modern and ancient texts. Previously, there were only 256
395possible ordinals for script characters. Texts were typically bound to a code
396page which mapped the ordinals to script characters. This lead to very much
397confusion especially with respect to internationalization (usually written as
398``i18n`` --- ``'i'`` + 18 characters + ``'n'``) of software. Unicode solves
399these problems by defining one code page for all scripts.
400
401Creating Unicode strings in Python is just as simple as creating normal
402strings::
403
404 >>> u'Hello World !'
405 u'Hello World !'
406
407The small ``'u'`` in front of the quote indicates that a Unicode string is
408supposed to be created. If you want to include special characters in the string,
409you can do so by using the Python *Unicode-Escape* encoding. The following
410example shows how::
411
412 >>> u'Hello\u0020World !'
413 u'Hello World !'
414
415The escape sequence ``\u0020`` indicates to insert the Unicode character with
416the ordinal value 0x0020 (the space character) at the given position.
417
418Other characters are interpreted by using their respective ordinal values
419directly as Unicode ordinals. If you have literal strings in the standard
420Latin-1 encoding that is used in many Western countries, you will find it
421convenient that the lower 256 characters of Unicode are the same as the 256
422characters of Latin-1.
423
424For experts, there is also a raw mode just like the one for normal strings. You
425have to prefix the opening quote with 'ur' to have Python use the
426*Raw-Unicode-Escape* encoding. It will only apply the above ``\uXXXX``
427conversion if there is an uneven number of backslashes in front of the small
428'u'. ::
429
430 >>> ur'Hello\u0020World !'
431 u'Hello World !'
432 >>> ur'Hello\\u0020World !'
433 u'Hello\\\\u0020World !'
434
435The raw mode is most useful when you have to enter lots of backslashes, as can
436be necessary in regular expressions.
437
438Apart from these standard encodings, Python provides a whole set of other ways
439of creating Unicode strings on the basis of a known encoding.
440
441.. index:: builtin: unicode
442
443The built-in function :func:`unicode` provides access to all registered Unicode
444codecs (COders and DECoders). Some of the more well known encodings which these
445codecs can convert are *Latin-1*, *ASCII*, *UTF-8*, and *UTF-16*. The latter two
446are variable-length encodings that store each Unicode character in one or more
447bytes. The default encoding is normally set to ASCII, which passes through
448characters in the range 0 to 127 and rejects any other characters with an error.
449When a Unicode string is printed, written to a file, or converted with
450:func:`str`, conversion takes place using this default encoding. ::
451
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)
462
463To convert a Unicode string into an 8-bit string using a specific encoding,
464Unicode objects provide an :func:`encode` method that takes one argument, the
465name of the encoding. Lowercase names for encodings are preferred. ::
466
467 >>> u"äöü".encode('utf-8')
468 '\xc3\xa4\xc3\xb6\xc3\xbc'
469
470If you have data in a specific encoding and want to produce a corresponding
471Unicode string from it, you can use the :func:`unicode` function with the
472encoding name as the second argument. ::
473
474 >>> unicode('\xc3\xa4\xc3\xb6\xc3\xbc', 'utf-8')
475 u'\xe4\xf6\xfc'
476
477
478.. _tut-lists:
479
480Lists
481-----
482
483Python knows a number of *compound* data types, used to group together other
484values. The most versatile is the *list*, which can be written as a list of
485comma-separated values (items) between square brackets. List items need not all
486have the same type. ::
487
488 >>> a = ['spam', 'eggs', 100, 1234]
489 >>> a
490 ['spam', 'eggs', 100, 1234]
491
492Like string indices, list indices start at 0, and lists can be sliced,
493concatenated and so on::
494
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!']
507
508Unlike strings, which are *immutable*, it is possible to change individual
509elements of a list::
510
511 >>> a
512 ['spam', 'eggs', 100, 1234]
513 >>> a[2] = a[2] + 23
514 >>> a
515 ['spam', 'eggs', 123, 1234]
516
517Assignment to slices is also possible, and this can even change the size of the
518list or clear it entirely::
519
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 []
540
541The built-in function :func:`len` also applies to lists::
542
Georg Brandl87426cb2007-11-09 13:08:48 +0000543 >>> a = ['a', 'b', 'c', 'd']
Georg Brandl8ec7f652007-08-15 14:28:01 +0000544 >>> len(a)
Georg Brandl87426cb2007-11-09 13:08:48 +0000545 4
Georg Brandl8ec7f652007-08-15 14:28:01 +0000546
547It is possible to nest lists (create lists containing other lists), for
548example::
549
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']
563
564Note that in the last example, ``p[1]`` and ``q`` really refer to the same
565object! We'll come back to *object semantics* later.
566
567
568.. _tut-firststeps:
569
570First Steps Towards Programming
571===============================
572
573Of course, we can use Python for more complicated tasks than adding two and two
574together. For instance, we can write an initial sub-sequence of the *Fibonacci*
575series as follows::
576
577 >>> # Fibonacci series:
578 ... # the sum of two elements defines the next
579 ... a, b = 0, 1
580 >>> while b < 10:
Georg Brandl35f88612008-01-06 22:05:40 +0000581 ... print b
582 ... a, b = b, a+b
Georg Brandl8ec7f652007-08-15 14:28:01 +0000583 ...
584 1
585 1
586 2
587 3
588 5
589 8
590
591This example introduces several new features.
592
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.
598
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).
607
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.
616
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::
622
623 >>> i = 256*256
624 >>> print 'The value of i is', i
625 The value of i is 65536
626
627 A trailing comma avoids the newline after the output::
628
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
635
636 Note that the interpreter inserts a newline before it prints the next prompt if
637 the last line was not completed.