Debian Codegraph @

Doc/tutorial/introduction.rst

raw
1 .. _tut-informal:
2
3 **********************************
4 An Informal Introduction to Python
5 **********************************
6
7 In the following examples, input and output are distinguished by the presence or
8 absence of prompts (:term:`>>>` and :term:`...`): 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.
13
14 .. only:: html
15
16 You can use the "Copy" button (it appears in the upper-right corner
17 when hovering over or tapping a code example), which strips prompts
18 and omits output, to copy and paste the input lines into your interpreter.
19
20 .. index:: single: # (hash); comment
21
22 Many of the examples in this manual, even those entered at the interactive
23 prompt, include comments. Comments in Python start with the hash character,
24 ``#``, and extend to the end of the physical line. A comment may appear at the
25 start of a line or following whitespace or code, but not within a string
26 literal. A hash character within a string literal is just a hash character.
27 Since comments are to clarify code and are not interpreted by Python, they may
28 be omitted when typing in examples.
29
30 Some examples::
31
32 # this is the first comment
33 spam = 1 # and this is the second comment
34 # ... and now a third!
35 text = "# This is not a comment because it's inside quotes."
36
37
38 .. _tut-calculator:
39
40 Using Python as a Calculator
41 ============================
42
43 Let's try some simple Python commands. Start the interpreter and wait for the
44 primary prompt, ``>>>``. (It shouldn't take long.)
45
46
47 .. _tut-numbers:
48
49 Numbers
50 -------
51
52 The interpreter acts as a simple calculator: you can type an expression into it
53 and it will write the value. Expression syntax is straightforward: the
54 operators ``+``, ``-``, ``*`` and ``/`` can be used to perform
55 arithmetic; parentheses (``()``) can be used for grouping.
56 For example::
57
58 >>> 2 + 2
59 4
60 >>> 50 - 5*6
61 20
62 >>> (50 - 5*6) / 4
63 5.0
64 >>> 8 / 5 # division always returns a floating-point number
65 1.6
66
67 The integer numbers (e.g. ``2``, ``4``, ``20``) have type :class:`int`,
68 the ones with a fractional part (e.g. ``5.0``, ``1.6``) have type
69 :class:`float`. We will see more about numeric types later in the tutorial.
70
71 Division (``/``) always returns a float. To do :term:`floor division` and
72 get an integer result you can use the ``//`` operator; to calculate
73 the remainder you can use ``%``::
74
75 >>> 17 / 3 # classic division returns a float
76 5.666666666666667
77 >>>
78 >>> 17 // 3 # floor division discards the fractional part
79 5
80 >>> 17 % 3 # the % operator returns the remainder of the division
81 2
82 >>> 5 * 3 + 2 # floored quotient * divisor + remainder
83 17
84
85 With Python, it is possible to use the ``**`` operator to calculate powers [#]_::
86
87 >>> 5 ** 2 # 5 squared
88 25
89 >>> 2 ** 7 # 2 to the power of 7
90 128
91
92 The equal sign (``=``) is used to assign a value to a variable. Afterwards, no
93 result is displayed before the next interactive prompt::
94
95 >>> width = 20
96 >>> height = 5 * 9
97 >>> width * height
98 900
99
100 If a variable is not "defined" (assigned a value), trying to use it will
101 give you an error::
102
103 >>> n # try to access an undefined variable
104 Traceback (most recent call last):
105 File "<stdin>", line 1, in <module>
106 NameError: name 'n' is not defined
107
108 There is full support for floating point; operators with mixed type operands
109 convert the integer operand to floating point::
110
111 >>> 4 * 3.75 - 1
112 14.0
113
114 In interactive mode, the last printed expression is assigned to the variable
115 ``_``. This means that when you are using Python as a desk calculator, it is
116 somewhat easier to continue calculations, for example::
117
118 >>> tax = 12.5 / 100
119 >>> price = 100.50
120 >>> price * tax
121 12.5625
122 >>> price + _
123 113.0625
124 >>> round(_, 2)
125 113.06
126
127 This variable should be treated as read-only by the user. Don't explicitly
128 assign a value to it --- you would create an independent local variable with the
129 same name masking the built-in variable with its magic behavior.
130
131 In addition to :class:`int` and :class:`float`, Python supports other types of
132 numbers, such as :class:`~decimal.Decimal` and :class:`~fractions.Fraction`.
133 Python also has built-in support for :ref:`complex numbers <typesnumeric>`,
134 and uses the ``j`` or ``J`` suffix to indicate the imaginary part
135 (e.g. ``3+5j``).
136
137
138 .. _tut-strings:
139
140 Text
141 ----
142
143 Python can manipulate text (represented by type :class:`str`, so-called
144 "strings") as well as numbers. This includes characters "``!``", words
145 "``rabbit``", names "``Paris``", sentences "``Got your back.``", etc.
146 "``Yay! :)``". They can be enclosed in single quotes (``'...'``) or double
147 quotes (``"..."``) with the same result [#]_.
148
149 .. code-block:: pycon
150
151 >>> 'spam eggs' # single quotes
152 'spam eggs'
153 >>> "Paris rabbit got your back :)! Yay!" # double quotes
154 'Paris rabbit got your back :)! Yay!'
155 >>> '1975' # digits and numerals enclosed in quotes are also strings
156 '1975'
157
158 To quote a quote, we need to "escape" it, by preceding it with ``\``.
159 Alternatively, we can use the other type of quotation marks::
160
161 >>> 'doesn\'t' # use \' to escape the single quote...
162 "doesn't"
163 >>> "doesn't" # ...or use double quotes instead
164 "doesn't"
165 >>> '"Yes," they said.'
166 '"Yes," they said.'
167 >>> "\"Yes,\" they said."
168 '"Yes," they said.'
169 >>> '"Isn\'t," they said.'
170 '"Isn\'t," they said.'
171
172 In the Python shell, the string definition and output string can look
173 different. The :func:`print` function produces a more readable output, by
174 omitting the enclosing quotes and by printing escaped and special characters::
175
176 >>> s = 'First line.\nSecond line.' # \n means newline
177 >>> s # without print(), special characters are included in the string
178 'First line.\nSecond line.'
179 >>> print(s) # with print(), special characters are interpreted, so \n produces new line
180 First line.
181 Second line.
182
183 If you don't want characters prefaced by ``\`` to be interpreted as
184 special characters, you can use *raw strings* by adding an ``r`` before
185 the first quote::
186
187 >>> print('C:\this\name') # here \t means tab, \n means newline
188 C: his
189 ame
190 >>> print(r'C:\this\name') # note the r before the quote
191 C:\this\name
192
193 There is one subtle aspect to raw strings: a raw string may not end in
194 an odd number of ``\`` characters; see
195 :ref:`the FAQ entry <faq-programming-raw-string-backslash>` for more information
196 and workarounds.
197
198 String literals can span multiple lines. One way is using triple-quotes:
199 ``"""..."""`` or ``'''...'''``. End-of-line characters are automatically
200 included in the string, but it's possible to prevent this by adding a ``\`` at
201 the end of the line. In the following example, the initial newline is not
202 included::
203
204 >>> print("""\
205 ... Usage: thingy [OPTIONS]
206 ... -h Display this usage message
207 ... -H hostname Hostname to connect to
208 ... """)
209 Usage: thingy [OPTIONS]
210 -h Display this usage message
211 -H hostname Hostname to connect to
212
213 >>>
214
215 Strings can be concatenated (glued together) with the ``+`` operator, and
216 repeated with ``*``::
217
218 >>> # 3 times 'un', followed by 'ium'
219 >>> 3 * 'un' + 'ium'
220 'unununium'
221
222 Two or more *string literals* (i.e. the ones enclosed between quotes) next
223 to each other are automatically concatenated. ::
224
225 >>> 'Py' 'thon'
226 'Python'
227
228 This feature is particularly useful when you want to break long strings::
229
230 >>> text = ('Put several strings within parentheses '
231 ... 'to have them joined together.')
232 >>> text
233 'Put several strings within parentheses to have them joined together.'
234
235 This only works with two literals though, not with variables or expressions::
236
237 >>> prefix = 'Py'
238 >>> prefix 'thon' # can't concatenate a variable and a string literal
239 File "<stdin>", line 1
240 prefix 'thon'
241 ^^^^^^
242 SyntaxError: invalid syntax
243 >>> ('un' * 3) 'ium'
244 File "<stdin>", line 1
245 ('un' * 3) 'ium'
246 ^^^^^
247 SyntaxError: invalid syntax
248
249 If you want to concatenate variables or a variable and a literal, use ``+``::
250
251 >>> prefix + 'thon'
252 'Python'
253
254 Strings can be *indexed* (subscripted), with the first character having index 0.
255 There is no separate character type; a character is simply a string of size
256 one::
257
258 >>> word = 'Python'
259 >>> word[0] # character in position 0
260 'P'
261 >>> word[5] # character in position 5
262 'n'
263
264 Indices may also be negative numbers, to start counting from the right::
265
266 >>> word[-1] # last character
267 'n'
268 >>> word[-2] # second-last character
269 'o'
270 >>> word[-6]
271 'P'
272
273 Note that since -0 is the same as 0, negative indices start from -1.
274
275 In addition to indexing, *slicing* is also supported. While indexing is used
276 to obtain individual characters, *slicing* allows you to obtain a substring::
277
278 >>> word[0:2] # characters from position 0 (included) to 2 (excluded)
279 'Py'
280 >>> word[2:5] # characters from position 2 (included) to 5 (excluded)
281 'tho'
282
283 Slice indices have useful defaults; an omitted first index defaults to zero, an
284 omitted second index defaults to the size of the string being sliced. ::
285
286 >>> word[:2] # character from the beginning to position 2 (excluded)
287 'Py'
288 >>> word[4:] # characters from position 4 (included) to the end
289 'on'
290 >>> word[-2:] # characters from the second-last (included) to the end
291 'on'
292
293 Note how the start is always included, and the end always excluded. This
294 makes sure that ``s[:i] + s[i:]`` is always equal to ``s``::
295
296 >>> word[:2] + word[2:]
297 'Python'
298 >>> word[:4] + word[4:]
299 'Python'
300
301 One way to remember how slices work is to think of the indices as pointing
302 *between* characters, with the left edge of the first character numbered 0.
303 Then the right edge of the last character of a string of *n* characters has
304 index *n*, for example::
305
306 +---+---+---+---+---+---+
307 | P | y | t | h | o | n |
308 +---+---+---+---+---+---+
309 0 1 2 3 4 5 6
310 -6 -5 -4 -3 -2 -1
311
312 The first row of numbers gives the position of the indices 0...6 in the string;
313 the second row gives the corresponding negative indices. The slice from *i* to
314 *j* consists of all characters between the edges labeled *i* and *j*,
315 respectively.
316
317 For non-negative indices, the length of a slice is the difference of the
318 indices, if both are within bounds. For example, the length of ``word[1:3]`` is
319 2.
320
321 Attempting to use an index that is too large will result in an error::
322
323 >>> word[42] # the word only has 6 characters
324 Traceback (most recent call last):
325 File "<stdin>", line 1, in <module>
326 IndexError: string index out of range
327
328 However, out of range slice indexes are handled gracefully when used for
329 slicing::
330
331 >>> word[4:42]
332 'on'
333 >>> word[42:]
334 ''
335
336 Python strings cannot be changed --- they are :term:`immutable`.
337 Therefore, assigning to an indexed position in the string results in an error::
338
339 >>> word[0] = 'J'
340 Traceback (most recent call last):
341 File "<stdin>", line 1, in <module>
342 TypeError: 'str' object does not support item assignment
343 >>> word[2:] = 'py'
344 Traceback (most recent call last):
345 File "<stdin>", line 1, in <module>
346 TypeError: 'str' object does not support item assignment
347
348 If you need a different string, you should create a new one::
349
350 >>> 'J' + word[1:]
351 'Jython'
352 >>> word[:2] + 'py'
353 'Pypy'
354
355 The built-in function :func:`len` returns the length of a string::
356
357 >>> s = 'supercalifragilisticexpialidocious'
358 >>> len(s)
359 34
360
361
362 .. seealso::
363
364 :ref:`textseq`
365 Strings are examples of *sequence types*, and support the common
366 operations supported by such types.
367
368 :ref:`string-methods`
369 Strings support a large number of methods for
370 basic transformations and searching.
371
372 :ref:`f-strings`
373 String literals that have embedded expressions.
374
375 :ref:`formatstrings`
376 Information about string formatting with :meth:`str.format`.
377
378 :ref:`old-string-formatting`
379 The old formatting operations invoked when strings are
380 the left operand of the ``%`` operator are described in more detail here.
381
382
383 .. _tut-lists:
384
385 Lists
386 -----
387
388 Python knows a number of *compound* data types, used to group together other
389 values. The most versatile is the *list*, which can be written as a list of
390 comma-separated values (items) between square brackets. Lists might contain
391 items of different types, but usually the items all have the same type. ::
392
393 >>> squares = [1, 4, 9, 16, 25]
394 >>> squares
395 [1, 4, 9, 16, 25]
396
397 Like strings (and all other built-in :term:`sequence` types), lists can be
398 indexed and sliced::
399
400 >>> squares[0] # indexing returns the item
401 1
402 >>> squares[-1]
403 25
404 >>> squares[-3:] # slicing returns a new list
405 [9, 16, 25]
406
407 Lists also support operations like concatenation::
408
409 >>> squares + [36, 49, 64, 81, 100]
410 [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
411
412 Unlike strings, which are :term:`immutable`, lists are a :term:`mutable`
413 type, i.e. it is possible to change their content::
414
415 >>> cubes = [1, 8, 27, 65, 125] # something's wrong here
416 >>> 4 ** 3 # the cube of 4 is 64, not 65!
417 64
418 >>> cubes[3] = 64 # replace the wrong value
419 >>> cubes
420 [1, 8, 27, 64, 125]
421
422 You can also add new items at the end of the list, by using
423 the :meth:`list.append` *method* (we will see more about methods later)::
424
425 >>> cubes.append(216) # add the cube of 6
426 >>> cubes.append(7 ** 3) # and the cube of 7
427 >>> cubes
428 [1, 8, 27, 64, 125, 216, 343]
429
430 Simple assignment in Python never copies data. When you assign a list
431 to a variable, the variable refers to the *existing list*.
432 Any changes you make to the list through one variable will be seen
433 through all other variables that refer to it.::
434
435 >>> rgb = ["Red", "Green", "Blue"]
436 >>> rgba = rgb
437 >>> id(rgb) == id(rgba) # they reference the same object
438 True
439 >>> rgba.append("Alph")
440 >>> rgb
441 ["Red", "Green", "Blue", "Alph"]
442
443 All slice operations return a new list containing the requested elements. This
444 means that the following slice returns a
445 :ref:`shallow copy <shallow_vs_deep_copy>` of the list::
446
447 >>> correct_rgba = rgba[:]
448 >>> correct_rgba[-1] = "Alpha"
449 >>> correct_rgba
450 ["Red", "Green", "Blue", "Alpha"]
451 >>> rgba
452 ["Red", "Green", "Blue", "Alph"]
453
454 Assignment to slices is also possible, and this can even change the size of the
455 list or clear it entirely::
456
457 >>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
458 >>> letters
459 ['a', 'b', 'c', 'd', 'e', 'f', 'g']
460 >>> # replace some values
461 >>> letters[2:5] = ['C', 'D', 'E']
462 >>> letters
463 ['a', 'b', 'C', 'D', 'E', 'f', 'g']
464 >>> # now remove them
465 >>> letters[2:5] = []
466 >>> letters
467 ['a', 'b', 'f', 'g']
468 >>> # clear the list by replacing all the elements with an empty list
469 >>> letters[:] = []
470 >>> letters
471 []
472
473 The built-in function :func:`len` also applies to lists::
474
475 >>> letters = ['a', 'b', 'c', 'd']
476 >>> len(letters)
477 4
478
479 It is possible to nest lists (create lists containing other lists), for
480 example::
481
482 >>> a = ['a', 'b', 'c']
483 >>> n = [1, 2, 3]
484 >>> x = [a, n]
485 >>> x
486 [['a', 'b', 'c'], [1, 2, 3]]
487 >>> x[0]
488 ['a', 'b', 'c']
489 >>> x[0][1]
490 'b'
491
492 .. _tut-firststeps:
493
494 First Steps Towards Programming
495 ===============================
496
497 Of course, we can use Python for more complicated tasks than adding two and two
498 together. For instance, we can write an initial sub-sequence of the
499 `Fibonacci series <https://en.wikipedia.org/wiki/Fibonacci_sequence>`_
500 as follows::
501
502 >>> # Fibonacci series:
503 >>> # the sum of two elements defines the next
504 >>> a, b = 0, 1
505 >>> while a < 10:
506 ... print(a)
507 ... a, b = b, a+b
508 ...
509 0
510 1
511 1
512 2
513 3
514 5
515 8
516
517 This example introduces several new features.
518
519 * The first line contains a *multiple assignment*: the variables ``a`` and ``b``
520 simultaneously get the new values 0 and 1. On the last line this is used again,
521 demonstrating that the expressions on the right-hand side are all evaluated
522 first before any of the assignments take place. The right-hand side expressions
523 are evaluated from the left to the right.
524
525 * The :keyword:`while` loop executes as long as the condition (here: ``a < 10``)
526 remains true. In Python, like in C, any non-zero integer value is true; zero is
527 false. The condition may also be a string or list value, in fact any sequence;
528 anything with a non-zero length is true, empty sequences are false. The test
529 used in the example is a simple comparison. The standard comparison operators
530 are written the same as in C: ``<`` (less than), ``>`` (greater than), ``==``
531 (equal to), ``<=`` (less than or equal to), ``>=`` (greater than or equal to)
532 and ``!=`` (not equal to).
533
534 * The *body* of the loop is *indented*: indentation is Python's way of grouping
535 statements. At the interactive prompt, you have to type a tab or space(s) for
536 each indented line. In practice you will prepare more complicated input
537 for Python with a text editor; all decent text editors have an auto-indent
538 facility. When a compound statement is entered interactively, it must be
539 followed by a blank line to indicate completion (since the parser cannot
540 guess when you have typed the last line). Note that each line within a basic
541 block must be indented by the same amount.
542
543 * The :func:`print` function writes the value of the argument(s) it is given.
544 It differs from just writing the expression you want to write (as we did
545 earlier in the calculator examples) in the way it handles multiple arguments,
546 floating-point quantities, and strings. Strings are printed without quotes,
547 and a space is inserted between items, so you can format things nicely, like
548 this::
549
550 >>> i = 256*256
551 >>> print('The value of i is', i)
552 The value of i is 65536
553
554 The keyword argument *end* can be used to avoid the newline after the output,
555 or end the output with a different string::
556
557 >>> a, b = 0, 1
558 >>> while a < 1000:
559 ... print(a, end=',')
560 ... a, b = b, a+b
561 ...
562 0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,
563
564
565 .. rubric:: Footnotes
566
567 .. [#] Since ``**`` has higher precedence than ``-``, ``-3**2`` will be
568 interpreted as ``-(3**2)`` and thus result in ``-9``. To avoid this
569 and get ``9``, you can use ``(-3)**2``.
570
571 .. [#] Unlike other languages, special characters such as ``\n`` have the
572 same meaning with both single (``'...'``) and double (``"..."``) quotes.
573 The only difference between the two is that within single quotes you don't
574 need to escape ``"`` (but you have to escape ``\'``) and vice versa.