3. An Informal Introduction to Python



Some examples:

# this is the first comment
spam = 1  # and this is the second comment
          # ... and now a third!

3.1. Using Python as a Calculator

Let’s try some simple Python commands. Start the interpreter and wait for the primary prompt, >>>. (It shouldn’t take long.)

3.1.1. Numbers

The interpreter acts as a simple calculator: you can type an expression at it and it will write the value. Expression syntax is straightforward: the operators +, -, * and / work just like in most other languages (for example, Pascal or C); parentheses (()) can be used for grouping. For example:

>>> 2 + 2
>>> 50 - 5*6
>>> (50 - 5*6) / 4
>>> 8 / 5  # division always returns a floating point number

The integer numbers (e.g. 2, 4, 20) have type int, the ones with a fractional part (e.g. 5.0, 1.6) have type float. We will see more about numeric types later in the tutorial.

Division (/) always returns a float. To do floor division and get an integer result (discarding any fractional result) you can use the // operator; to calculate the remainder you can use %:

>>> 17 / 3  # classic division returns a float
>>> 17 // 3  # floor division discards the fractional part

With Python, it is possible to use the ** operator to calculate powers [1]:

>>> 5 ** 2  # 5 squared

The equal sign (=) is used to assign a value to a variable. Afterwards, no result is displayed before the next interactive prompt:

>>> width = 20
>>> height = 5 * 9
>>> width * height

If a variable is not “defined” (assigned a value), trying to use it will give you an error:

>>> n  # try to access an undefined variable
Traceback (most recent call last):
NameError: name 'n' is not defined


>>> 3 * 3.75 / 1.5
>>> 7.0 / 2

In interactive mode, the last printed expression is assigned to the variable _. This means that when you are using Python as a desk calculator, it is somewhat easier to continue calculations, for example:

>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
>>> price + _
>>> round(_, 2)

This variable should be treated as read-only by the user. Don’t explicitly assign a value to it — you would create an independent local variable with the same name masking the built-in variable with its magic behavior.

In addition to int and float, Python supports other types of numbers, such as Decimal and Fraction. Python also has built-in support for complex numbers, and uses the j or J suffix to indicate the imaginary part (e.g. 3+5j).

3.1.2. Strings

Besides numbers, Python can also manipulate strings, which can be expressed in several ways. They can be enclosed in single quotes ('...') or double quotes ("...") with the same result [2]. \ can be used to escape quotes:

>>> 'spam eggs'  # single quotes
'spam eggs'
>>> '"Yes," he said.'
'"Yes," he said.'
>>> "\"Yes,\" he said."
'"Yes," he said.'
>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'


'"Isn\'t," she said.'
>>> print('"Isn\'t," she said.')
"Isn't," she said.
>>> s  # without print(), \n is included in the output
'First line.\nSecond line.'
>>> print(s)  # with print(), \n produces a new line
First line.
Second line.

If you don’t want characters prefaced by \ to be interpreted as special characters, you can use raw strings by adding an r before the first quote:

>>> print('C:\some\name')  # here \n means newline!
>>> print(r'C:\some\name')  # note the r before the quote

String literals can span multiple lines. One way is using triple-quotes: """...""" or '''...'''. End of lines are automatically included in the string, but it’s possible to prevent this by adding a \ at the end of the line. The following example:

Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to


Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to


>>> 3 * 'un' + 'ium'

Two or more string literals (i.e. the ones enclosed between quotes) next to each other are automatically concatenated.

>>> 'Py' 'thon'


>>> prefix = 'Py'
SyntaxError: invalid syntax
SyntaxError: invalid syntax

If you want to concatenate variables or a variable and a literal, use +:

>>> prefix + 'thon'


...         'to have them joined together.')
>>> text


>>> word = 'Python'
>>> word[0]  # character in position 0
>>> word[5]  # character in position 5


>>> word[-1]  # last character
>>> word[-6]


In addition to indexing, slicing is also supported. While indexing is used to obtain individual characters, slicing allows you to obtain substring:


Note how the start is always included, and the end always excluded. This makes sure that s[:i] + s[i:] is always equal to s:





 0   1   2   3   4   5   6
-6  -5  -4  -3  -2  -1

The first row of numbers gives the position of the indices 0...6 in the string; the second row gives the corresponding negative indices. The slice from i to j consists of all characters between the edges labeled i and j, respectively.

For non-negative indices, the length of a slice is the difference of the indices, if both are within bounds. For example, the length of word[1:3] is 2.


Traceback (most recent call last):
IndexError: string index out of range


>>> word[4:42]
>>> word[42:]

Python strings cannot be changed — they are immutable. Therefore, assigning to an indexed position in the string results in an error:

>>> word[0] = 'J'
TypeError: 'str' object does not support item assignment
>>> word[2:] = 'py'
TypeError: 'str' object does not support item assignment


>>> 'J' + word[1:]
>>> word[:2] + 'py'


>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)

See also

Text Sequence Type — str
Strings are examples of sequence types, and support the common operations supported by such types.
String Methods
Strings support a large number of methods for basic transformations and searching.
Format String Syntax
Information about string formatting with str.format().
printf-style String Formatting
The old formatting operations invoked when strings and Unicode strings are the left operand of the % operator are described in more detail here.

3.1.3. Lists

Python knows a number of compound data types, used to group together other values. The most versatile is the list, which can be written as a list of comma-separated values (items) between square brackets. Lists might contain items of different types, but usually the items all have the same type.

>>> squares
[1, 4, 9, 16, 25]

Like strings (and all other built-in sequence type), lists can be indexed and sliced:

>>> squares[0]  # indexing returns the item
>>> squares[-1]
[9, 16, 25]


>>> squares[:]
[1, 4, 9, 16, 25]

Lists also support operations like concatenation:


Unlike strings, which are immutable, lists are a mutable type, i.e. it is possible to change their content:

>>> cubes
[1, 8, 27, 64, 125]

You can also add new items at the end of the list, by using the append() method (we will see more about methods later):

>>> cubes


>>> letters
>>> # replace some values
>>> letters
>>> # now remove them
>>> letters[2:5] = []
>>> letters
>>> letters[:] = []
>>> letters

The built-in function len() also applies to lists:

>>> len(letters)


>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
>>> x[0]
>>> x[0][1]

3.2. First Steps Towards Programming

Of course, we can use Python for more complicated tasks than adding two and two together. For instance, we can write an initial sub-sequence of the Fibonacci series as follows:

>>> # Fibonacci series:
... # the sum of two elements defines the next
... a, b = 0, 1
>>> while b < 10:
...     print(b)
...     a, b = b, a+b

This example introduces several new features.

  • The first line contains a multiple assignment: the variables a and b simultaneously get the new values 0 and 1. On the last line this is used again, demonstrating that the expressions on the right-hand side are all evaluated first before any of the assignments take place. The right-hand side expressions are evaluated from the left to the right.

  • The while loop executes as long as the condition (here: b < 10) remains true. In Python, like in C, any non-zero integer value is true; zero is false. The condition may also be a string or list value, in fact any sequence; anything with a non-zero length is true, empty sequences are false. The test used in the example is a simple comparison. The standard comparison operators are written the same as in C: < (less than), > (greater than), == (equal to), <= (less than or equal to), >= (greater than or equal to) and != (not equal to).


  • The print() function writes the value of the argument(s) it is given. It differs from just writing the expression you want to write (as we did earlier in the calculator examples) in the way it handles multiple arguments, floating point quantities, and strings. Strings are printed without quotes, and a space is inserted between items, so you can format things nicely, like this:

    >>> i = 256*256
    >>> print('The value of i is', i)
    The value of i is 65536

    The keyword argument end can be used to avoid the newline after the output, or end the output with a different string:

    >>> a, b = 0, 1
    >>> while b < 1000:
    ...     print(b, end=',')
    ...     a, b = b, a+b


[1]Since ** has higher precedence than -, -3**2 will be interpreted as -(3**2) and thus result in -9. To avoid this and get 9, you can use (-3)**2.
[2]Unlike other languages, special characters such as \n have the same meaning with both single ('...') and double ("...") quotes. The only difference between the two is that within single quotes you don’t need to escape " (but you have to escape \') and vice versa.