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