9. Some additional topics
9.1. Operators
[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
[1]:
1
9.2. List Comprehensions
[2]:
[x**2 for x in {1, 2, 3}]
[2]:
[1, 4, 9]
[3]:
[x**2 for x in {1, 2, 3, 4, 5} if x >= 3]
[3]:
[9, 16, 25]
[4]:
[
x*10 + y**3
for x in {1, 100}
for y in [1, 5, 7]
]
[4]:
[11, 135, 353, 1001, 1125, 1343]
[5]:
[
x*10 + y**3
for x in {1, 100}
for y in [1, 5, 700]
if x >= y
]
[5]:
[11, 1001, 1125]
[6]:
[
(x, y)
for x in {1, 100}
for y in [1, 5, 700]
if x >= y
]
[6]:
[(1, 1), (100, 1), (100, 5)]
9.3. Exceptions
[7]:
try:
this_var_does_not_exist
except NameError:
print("Exception catched")
Exception catched
You can also raise the exception after catching it:
[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:
[ ]:
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:
[ ]:
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/.