Home | History | Annotate | Download | only in tutorial
      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 .. index:: single: # (hash); comment
     15 
     16 Many of the examples in this manual, even those entered at the interactive
     17 prompt, 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
     19 start of a line or following whitespace or code, but not within a string
     20 literal.  A hash character within a string literal is just a hash character.
     21 Since comments are to clarify code and are not interpreted by Python, they may
     22 be omitted when typing in examples.
     23 
     24 Some 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 
     34 Using Python as a Calculator
     35 ============================
     36 
     37 Let's try some simple Python commands.  Start the interpreter and wait for the
     38 primary prompt, ``>>>``.  (It shouldn't take long.)
     39 
     40 
     41 .. _tut-numbers:
     42 
     43 Numbers
     44 -------
     45 
     46 The interpreter acts as a simple calculator: you can type an expression at it
     47 and it will write the value.  Expression syntax is straightforward: the
     48 operators ``+``, ``-``, ``*`` and ``/`` work just like in most other languages
     49 (for example, Pascal or C); parentheses (``()``) can be used for grouping.
     50 For 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 
     61 The integer numbers (e.g. ``2``, ``4``, ``20``) have type :class:`int`,
     62 the 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 
     65 Division (``/``) always returns a float.  To do :term:`floor division` and
     66 get an integer result (discarding any fractional result) you can use the ``//``
     67 operator; 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 
     79 With 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 
     86 The equal sign (``=``) is used to assign a value to a variable. Afterwards, no
     87 result is displayed before the next interactive prompt::
     88 
     89    >>> width = 20
     90    >>> height = 5 * 9
     91    >>> width * height
     92    900
     93 
     94 If a variable is not "defined" (assigned a value), trying to use it will
     95 give 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 
    102 There is full support for floating point; operators with mixed type operands
    103 convert the integer operand to floating point::
    104 
    105    >>> 4 * 3.75 - 1
    106    14.0
    107 
    108 In 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
    110 somewhat 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 
    121 This variable should be treated as read-only by the user.  Don't explicitly
    122 assign a value to it --- you would create an independent local variable with the
    123 same name masking the built-in variable with its magic behavior.
    124 
    125 In addition to :class:`int` and :class:`float`, Python supports other types of
    126 numbers, such as :class:`~decimal.Decimal` and :class:`~fractions.Fraction`.
    127 Python also has built-in support for :ref:`complex numbers <typesnumeric>`,
    128 and uses the ``j`` or ``J`` suffix to indicate the imaginary part
    129 (e.g. ``3+5j``).
    130 
    131 
    132 .. _tut-strings:
    133 
    134 Strings
    135 -------
    136 
    137 Besides numbers, Python can also manipulate strings, which can be expressed
    138 in several ways.  They can be enclosed in single quotes (``'...'``) or
    139 double quotes (``"..."``) with the same result [#]_.  ``\`` can be used
    140 to 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 
    155 In the interactive interpreter, the output string is enclosed in quotes and
    156 special characters are escaped with backslashes.  While this might sometimes
    157 look different from the input (the enclosing quotes could change), the two
    158 strings are equivalent.  The string is enclosed in double quotes if
    159 the string contains a single quote and no double quotes, otherwise it is
    160 enclosed in single quotes.  The :func:`print` function produces a more
    161 readable output, by omitting the enclosing quotes and by printing escaped
    162 and 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 
    175 If you don't want characters prefaced by ``\`` to be interpreted as
    176 special characters, you can use *raw strings* by adding an ``r`` before
    177 the 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 
    185 String literals can span multiple lines.  One way is using triple-quotes:
    186 ``"""..."""`` or ``'''...'''``.  End of lines are automatically
    187 included in the string, but it's possible to prevent this by adding a ``\`` at
    188 the 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 
    196 produces 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 
    204 Strings can be concatenated (glued together) with the ``+`` operator, and
    205 repeated with ``*``::
    206 
    207    >>> # 3 times 'un', followed by 'ium'
    208    >>> 3 * 'un' + 'ium'
    209    'unununium'
    210 
    211 Two or more *string literals* (i.e. the ones enclosed between quotes) next
    212 to each other are automatically concatenated. ::
    213 
    214    >>> 'Py' 'thon'
    215    'Python'
    216 
    217 This 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 
    224 This 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 
    238 If you want to concatenate variables or a variable and a literal, use ``+``::
    239 
    240    >>> prefix + 'thon'
    241    'Python'
    242 
    243 Strings can be *indexed* (subscripted), with the first character having index 0.
    244 There is no separate character type; a character is simply a string of size
    245 one::
    246 
    247    >>> word = 'Python'
    248    >>> word[0]  # character in position 0
    249    'P'
    250    >>> word[5]  # character in position 5
    251    'n'
    252 
    253 Indices 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 
    262 Note that since -0 is the same as 0, negative indices start from -1.
    263 
    264 In addition to indexing, *slicing* is also supported.  While indexing is used
    265 to 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 
    272 Note how the start is always included, and the end always excluded.  This
    273 makes 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 
    280 Slice indices have useful defaults; an omitted first index defaults to zero, an
    281 omitted 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 
    290 One 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.
    292 Then the right edge of the last character of a string of *n* characters has
    293 index *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 
    301 The first row of numbers gives the position of the indices 0...6 in the string;
    302 the 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*,
    304 respectively.
    305 
    306 For non-negative indices, the length of a slice is the difference of the
    307 indices, if both are within bounds.  For example, the length of ``word[1:3]`` is
    308 2.
    309 
    310 Attempting 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 
    317 However, out of range slice indexes are handled gracefully when used for
    318 slicing::
    319 
    320    >>> word[4:42]
    321    'on'
    322    >>> word[42:]
    323    ''
    324 
    325 Python strings cannot be changed --- they are :term:`immutable`.
    326 Therefore, 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 
    337 If 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 
    344 The 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 
    374 Lists
    375 -----
    376 
    377 Python knows a number of *compound* data types, used to group together other
    378 values.  The most versatile is the *list*, which can be written as a list of
    379 comma-separated values (items) between square brackets.  Lists might contain
    380 items 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 
    386 Like strings (and all other built-in :term:`sequence` type), lists can be
    387 indexed 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 
    396 All slice operations return a new list containing the requested elements.  This
    397 means that the following slice returns a new (shallow) copy of the list::
    398 
    399    >>> squares[:]
    400    [1, 4, 9, 16, 25]
    401 
    402 Lists also support operations like concatenation::
    403 
    404    >>> squares + [36, 49, 64, 81, 100]
    405    [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
    406 
    407 Unlike strings, which are :term:`immutable`, lists are a :term:`mutable`
    408 type, i.e. it is possible to change their content::
    409 
    410     >>> cubes = [1, 8, 27, 65, 125]  # something's wrong here
    411     >>> 4 ** 3  # the cube of 4 is 64, not 65!
    412     64
    413     >>> cubes[3] = 64  # replace the wrong value
    414     >>> cubes
    415     [1, 8, 27, 64, 125]
    416 
    417 You can also add new items at the end of the list, by using
    418 the :meth:`~list.append` *method* (we will see more about methods later)::
    419 
    420    >>> cubes.append(216)  # add the cube of 6
    421    >>> cubes.append(7 ** 3)  # and the cube of 7
    422    >>> cubes
    423    [1, 8, 27, 64, 125, 216, 343]
    424 
    425 Assignment to slices is also possible, and this can even change the size of the
    426 list or clear it entirely::
    427 
    428    >>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
    429    >>> letters
    430    ['a', 'b', 'c', 'd', 'e', 'f', 'g']
    431    >>> # replace some values
    432    >>> letters[2:5] = ['C', 'D', 'E']
    433    >>> letters
    434    ['a', 'b', 'C', 'D', 'E', 'f', 'g']
    435    >>> # now remove them
    436    >>> letters[2:5] = []
    437    >>> letters
    438    ['a', 'b', 'f', 'g']
    439    >>> # clear the list by replacing all the elements with an empty list
    440    >>> letters[:] = []
    441    >>> letters
    442    []
    443 
    444 The built-in function :func:`len` also applies to lists::
    445 
    446    >>> letters = ['a', 'b', 'c', 'd']
    447    >>> len(letters)
    448    4
    449 
    450 It is possible to nest lists (create lists containing other lists), for
    451 example::
    452 
    453    >>> a = ['a', 'b', 'c']
    454    >>> n = [1, 2, 3]
    455    >>> x = [a, n]
    456    >>> x
    457    [['a', 'b', 'c'], [1, 2, 3]]
    458    >>> x[0]
    459    ['a', 'b', 'c']
    460    >>> x[0][1]
    461    'b'
    462 
    463 .. _tut-firststeps:
    464 
    465 First Steps Towards Programming
    466 ===============================
    467 
    468 Of course, we can use Python for more complicated tasks than adding two and two
    469 together.  For instance, we can write an initial sub-sequence of the
    470 `Fibonacci series <https://en.wikipedia.org/wiki/Fibonacci_number>`_
    471 as follows::
    472 
    473    >>> # Fibonacci series:
    474    ... # the sum of two elements defines the next
    475    ... a, b = 0, 1
    476    >>> while a < 10:
    477    ...     print(a)
    478    ...     a, b = b, a+b
    479    ...
    480    0
    481    1
    482    1
    483    2
    484    3
    485    5
    486    8
    487 
    488 This example introduces several new features.
    489 
    490 * The first line contains a *multiple assignment*: the variables ``a`` and ``b``
    491   simultaneously get the new values 0 and 1.  On the last line this is used again,
    492   demonstrating that the expressions on the right-hand side are all evaluated
    493   first before any of the assignments take place.  The right-hand side expressions
    494   are evaluated  from the left to the right.
    495 
    496 * The :keyword:`while` loop executes as long as the condition (here: ``a < 10``)
    497   remains true.  In Python, like in C, any non-zero integer value is true; zero is
    498   false.  The condition may also be a string or list value, in fact any sequence;
    499   anything with a non-zero length is true, empty sequences are false.  The test
    500   used in the example is a simple comparison.  The standard comparison operators
    501   are written the same as in C: ``<`` (less than), ``>`` (greater than), ``==``
    502   (equal to), ``<=`` (less than or equal to), ``>=`` (greater than or equal to)
    503   and ``!=`` (not equal to).
    504 
    505 * The *body* of the loop is *indented*: indentation is Python's way of grouping
    506   statements.  At the interactive prompt, you have to type a tab or space(s) for
    507   each indented line.  In practice you will prepare more complicated input
    508   for Python with a text editor; all decent text editors have an auto-indent
    509   facility.  When a compound statement is entered interactively, it must be
    510   followed by a blank line to indicate completion (since the parser cannot
    511   guess when you have typed the last line).  Note that each line within a basic
    512   block must be indented by the same amount.
    513 
    514 * The :func:`print` function writes the value of the argument(s) it is given.
    515   It differs from just writing the expression you want to write (as we did
    516   earlier in the calculator examples) in the way it handles multiple arguments,
    517   floating point quantities, and strings.  Strings are printed without quotes,
    518   and a space is inserted between items, so you can format things nicely, like
    519   this::
    520 
    521      >>> i = 256*256
    522      >>> print('The value of i is', i)
    523      The value of i is 65536
    524 
    525   The keyword argument *end* can be used to avoid the newline after the output,
    526   or end the output with a different string::
    527 
    528      >>> a, b = 0, 1
    529      >>> while a < 1000:
    530      ...     print(a, end=',')
    531      ...     a, b = b, a+b
    532      ...
    533      0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,
    534 
    535 
    536 .. rubric:: Footnotes
    537 
    538 .. [#] Since ``**`` has higher precedence than ``-``, ``-3**2`` will be
    539    interpreted as ``-(3**2)`` and thus result in ``-9``.  To avoid this
    540    and get ``9``, you can use ``(-3)**2``.
    541 
    542 .. [#] Unlike other languages, special characters such as ``\n`` have the
    543    same meaning with both single (``'...'``) and double (``"..."``) quotes.
    544    The only difference between the two is that within single quotes you don't
    545    need to escape ``"`` (but you have to escape ``\'``) and vice versa.
    546