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