Module 03 - An Informal Introduction to Python

Python Example


In [86]:
from __future__ import print_function
# this is the first comment
spam = 1  # and this is the second comment
          # ... and now a third!
text = "# This is not a comment because it's inside quotes."
print(spam)
print(text)


1
# This is not a comment because it's inside quotes.

Using Python as a Calculator - Numbers

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:


In [2]:
2 + 2


Out[2]:
4

In [3]:
50 - 5*6


Out[3]:
20

In [4]:
(50 - 5.0*6) / 4


Out[4]:
5.0

In [5]:
8 / 5.0


Out[5]:
1.6
  • 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.


In [6]:
type(2)


Out[6]:
int

In [7]:
type(5.0)


Out[7]:
float

The return type of a division (/) operation depends on its operands.

If both operands are of type int, floor division is performed and an int is returned.

If either operand is a float, classic division is performed and a float is returned.

The // operator is also provided for doing floor division no matter what the operands are.

The remainder can be calculated with the % operator:


In [8]:
17 / 3  # int / int -> int


Out[8]:
5.666666666666667

In [9]:
17 / 3.0  # int / float -> float


Out[9]:
5.666666666666667

In [10]:
17 // 3.0  # explicit floor division discards the fractional part


Out[10]:
5.0

In [11]:
17 % 3  # the % operator returns the remainder of the division


Out[11]:
2

In [12]:
5 * 3 + 2  # result * divisor + remainder


Out[12]:
17

With Python, it is possible to use the ** operator to calculate powers


In [13]:
5 ** 2  # 5 squared


Out[13]:
25

In [14]:
2 ** 7  # 2 to the power of 7


Out[14]:
128

The equal sign (=) is used to assign a value to a variable.

Afterwards, no result is displayed before the next cell.


In [15]:
width = 20

In [16]:
height = 5 * 9

In [17]:
width * height


Out[17]:
900

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


In [18]:
n


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-18-fe13119fb084> in <module>()
----> 1 n

NameError: name 'n' is not defined

There is full support for floating point; operators with mixed type operands convert the integer operand to floating point:


In [19]:
3 * 3.75 / 1.5


Out[19]:
7.5

In [20]:
7.0 / 2


Out[20]:
3.5

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:


In [21]:
tax = 12.5 / 100
price = 100.50
price * tax


Out[21]:
12.5625

In [22]:
price + _


Out[22]:
113.0625

In [23]:
round(_, 2)


Out[23]:
113.06

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).

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:


In [24]:
'spam eggs'  # single quotes


Out[24]:
'spam eggs'

In [25]:
'doesn\'t'  # use \' to escape the single quote...


Out[25]:
"doesn't"

In [26]:
"doesn't"  # ...or use double quotes instead


Out[26]:
"doesn't"

In [27]:
'"Yes," he said.'


Out[27]:
'"Yes," he said.'

In [28]:
"\"Yes,\" he said."


Out[28]:
'"Yes," he said.'

In [29]:
'"Isn\'t," she said.'


Out[29]:
'"Isn\'t," she said.'

In the interactive interpreter, the output string is enclosed in quotes and special characters are escaped with backslashes.

While this might sometimes look different from the input (the enclosing quotes could change), the two strings are equivalent.

The string is enclosed in double quotes if the string contains a single quote and no double quotes, otherwise it is enclosed in single quotes.

The print statement produces a more readable output, by omitting the enclosing quotes and by printing escaped and special characters:


In [30]:
'"Isn\'t," she said.'


Out[30]:
'"Isn\'t," she said.'

In [31]:
print('"Isn\'t," she said.')


"Isn't," she said.

In [32]:
s = 'First line.\nSecond line.'  # \n means newline
s  # without print, \n is included in the output


Out[32]:
'First line.\nSecond line.'

In [33]:
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:


In [34]:
print('C:\some\name')  # here \n means newline!


C:\some
ame

In [35]:
print(r'C:\some\name')  # note the r before the quote


C:\some\name

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:


In [36]:
print("""\
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

Strings can be concatenated (glued together) with the + operator, and repeated with *:


In [37]:
# 3 times 'un', followed by 'ium'
3 * 'un' + 'ium'


Out[37]:
'unununium'

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


In [38]:
'Py' 'thon'


Out[38]:
'Python'

This only works with two literals though, not with variables or expressions:


In [39]:
prefix = 'Py'
prefix 'thon'  # can't concatenate a variable and a string literal


  File "<ipython-input-39-b72a098629bc>", line 2
    prefix 'thon'  # can't concatenate a variable and a string literal
                ^
SyntaxError: invalid syntax

In [40]:
('un' * 3) 'ium'


  File "<ipython-input-40-826b8aeb7d3b>", line 1
    ('un' * 3) 'ium'
                   ^
SyntaxError: invalid syntax

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


In [41]:
prefix = 'Py'
prefix + 'thon'


Out[41]:
'Python'

This feature is particularly useful when you want to break long strings:


In [42]:
text = ('Put several strings within parentheses '
        'to have them joined together.')
text


Out[42]:
'Put several strings within parentheses to have them joined together.'

String Indexing

Strings can be indexed (subscripted), with the first character having index 0.

There is no separate character type; a character is simply a string of size one:


In [43]:
word = 'Python'
word[0]  # character in position 0


Out[43]:
'P'

In [44]:
word[5]  # character in position 5


Out[44]:
'n'

Indices may also be negative numbers, to start counting from the right:


In [45]:
word[-1]  # last character


Out[45]:
'n'

In [46]:
word[-2]  # second-last character


Out[46]:
'o'

In [47]:
word[-6]


Out[47]:
'P'

Note that since -0 is the same as 0, negative indices start from -1.

Slicing

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


In [48]:
word[0:2]  # characters from position 0 (included) to 2 (excluded)


Out[48]:
'Py'

In [49]:
word[2:5]  # characters from position 2 (included) to 5 (excluded)


Out[49]:
'tho'

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:


In [50]:
word[:2] + word[2:]


Out[50]:
'Python'

In [51]:
word[:4] + word[4:]


Out[51]:
'Python'

Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.


In [52]:
word[:2]   # character from the beginning to position 2 (excluded)


Out[52]:
'Py'

In [53]:
word[4:]   # characters from position 4 (included) to the end


Out[53]:
'on'

In [54]:
word[-2:]  # characters from the second-last (included) to the end


Out[54]:
'on'

One way to remember how slices work is to think of the indices as pointing between characters, with the left edge of the first character numbered 0.

Then the right edge of the last character of a string of n characters has index n, for example:

 +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
 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.

Attempting to use an index that is too large will result in an error:


In [55]:
word[42]  # the word only has 6 characters


---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-55-5acb91c95ae6> in <module>()
----> 1 word[42]  # the word only has 6 characters

IndexError: string index out of range

However, out of range slice indexes are handled gracefully when used for slicing:


In [56]:
word[4:42]


Out[56]:
'on'

In [57]:
word[42:]


Out[57]:
''

Python strings cannot be changed — they are immutable.

Therefore, assigning to an indexed position in the string results in an error:


In [58]:
word[0] = 'J'


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-58-197b67ffdd83> in <module>()
----> 1 word[0] = 'J'

TypeError: 'str' object does not support item assignment

In [59]:
word[2:] = 'py'


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-59-0786521edfdd> in <module>()
----> 1 word[2:] = 'py'

TypeError: 'str' object does not support item assignment

If you need a different string, you should create a new one:


In [60]:
'J' + word[1:]


Out[60]:
'Jython'

In [61]:
word[:2] + 'py'


Out[61]:
'Pypy'

The built-in function len() returns the length of a string:


In [62]:
s = 'supercalifragilisticexpialidocious'
len(s)


Out[62]:
34

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.


In [63]:
squares = [1, 4, 9, 16, 25]
squares


Out[63]:
[1, 4, 9, 16, 25]

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


In [64]:
squares[0]  # indexing returns the item


Out[64]:
1

In [65]:
squares[-1]


Out[65]:
25

In [66]:
squares[-3:]  # slicing returns a new list


Out[66]:
[9, 16, 25]

Slicing

All slice operations return a new list containing the requested elements.

This means that the following slice returns a new (shallow) copy of the list:


In [67]:
squares[:]


Out[67]:
[1, 4, 9, 16, 25]

Concatenation

Lists also supports operations like concatenation:


In [68]:
squares + [36, 49, 64, 81, 100]


Out[68]:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Mutable

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


In [69]:
cubes = [1, 8, 27, 65, 125]  # something's wrong here
4 ** 3  # the cube of 4 is 64, not 65!


Out[69]:
64

In [70]:
cubes[3] = 64  # replace the wrong value
cubes


Out[70]:
[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):


In [71]:
cubes.append(216)  # add the cube of 6
cubes.append(7 ** 3)  # and the cube of 7
cubes


Out[71]:
[1, 8, 27, 64, 125, 216, 343]

Assignment to slices is also possible, and this can even change the size of the list or clear it entirely:


In [72]:
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
letters


Out[72]:
['a', 'b', 'c', 'd', 'e', 'f', 'g']

In [73]:
# replace some values
letters[2:5] = ['C', 'D', 'E']
letters


Out[73]:
['a', 'b', 'C', 'D', 'E', 'f', 'g']

In [74]:
# now remove them
letters[2:5] = []
letters


Out[74]:
['a', 'b', 'f', 'g']

In [75]:
# clear the list by replacing all the elements with an empty list
letters[:] = []
letters


Out[75]:
[]

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


In [76]:
letters = ['a', 'b', 'c', 'd']
len(letters)


Out[76]:
4

Nested Lists

It is possible to nest lists (create lists containing other lists), for example:


In [77]:
a = ['a', 'b', 'c']
n = [1, 2, 3]
x = [a, n]
x


Out[77]:
[['a', 'b', 'c'], [1, 2, 3]]

In [78]:
x[0]


Out[78]:
['a', 'b', 'c']

In [79]:
x[0][1]


Out[79]:
'b'

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:


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


1
1
2
3
5
8

This example introduces several new features:

Multiple Assignment

a, b = 0, 1
while b < 10:
    print(b)
    a, b = b, a+b

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.

While Loop

a, b = 0, 1
while b < 10:
    print(b)
    a, b = b, a+b

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).

Indentation

a, b = 0, 1
while b < 10:
    print(b)
    a, b = b, a+b

The body of the loop is indented: indentation is Python’s way of grouping statements.

At the interactive prompt, you have to type a tab or space(s) for each indented line.

In practice you will prepare more complicated input for Python with a text editor; all decent text editors have an auto-indent facility.

When a compound statement is entered interactively, it must be followed by a blank line to indicate completion (since the parser cannot guess when you have typed the last line).

Note that each line within a basic block must be indented by the same amount.

Printing Non-Strings

a, b = 0, 1
while b < 10:
    print(b)
    a, b = b, a+b

The print statement writes the value of the expression(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 expressions and strings.

Strings are printed without quotes, and a space is inserted between items, so you can format things nicely, like this:


In [82]:
i = 256*256
print('The value of i is', i)


The value of i is 65536

A trailing comma avoids the newline after the output:


In [85]:
a, b = 0, 1
while b < 1000:
    print(b,end=' ')
    a, b = b, a+b


1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987