9. Some additional topics

9.1. Operators

In [1]:
#common operations
23 + 42
32 - 32
12.4 * 2
13 / 3

#power
2 ** 3

#integer division
13 // 3

#modulus operator (rest of the division)
13 % 3
Out[1]:
1

9.2. List Comprehensions

In [2]:
[x**2 for x in {1, 2, 3}]
Out[2]:
[1, 4, 9]
In [3]:
[x**2 for x in {1, 2, 3, 4, 5} if x >= 3]
Out[3]:
[9, 16, 25]
In [4]:
[
 x*10 + y**3
 for x in {1, 100}
 for y in [1, 5, 7]
]
Out[4]:
[11, 135, 353, 1001, 1125, 1343]
In [5]:
[
 x*10 + y**3
 for x in {1, 100}
 for y in [1, 5, 700]
 if x >= y
]
Out[5]:
[11, 1001, 1125]
In [6]:
[
 (x, y)
 for x in {1, 100}
 for y in [1, 5, 700]
 if x >= y
]
Out[6]:
[(1, 1), (100, 1), (100, 5)]

9.3. Exceptions

In [7]:
try:
    this_var_does_not_exist
except NameError:
    print("Exception catched")
Exception catched

You can also raise the exception after catching it:

In [9]:
try:
    this_var_does_not_exist
except NameError as e:
    print("Exception catched, but we will re-raise it below")
    #Uncoment below to reraise it:
    #raise e
Exception catched, but we will re-raise it below

9.4. Serialization

You can use the package pickle to save objects to file:

In [ ]:
import pickle
a = [3, 2, 21, 3]

#Save list to a file
f = open("file_to_save.pkl", "wb")
pickle.dump(a, f)
f.close()

And later reload it using method load:

In [ ]:
import pickle
f = open("file_to_save.pkl", "rb")
a = pickle.load(f)
f.close()

9.5. Jupyter notebooks

Jupyter notebook allows one to create pages/applets containing live Python code and markup with support to equations and much more. It is usefull, for example, for presentations and sharing. See http://jupyter.org/.