Installation

Make sure to have all the required software installed after proceeding. For installation help, please consult the school guide.

Python Basics


In [ ]:
print('Hello World!')

Basic Math Operations


In [ ]:
print(3 + 5)
print(3 - 5)
print(3 * 5)
print(3 ** 5)

In [ ]:
# Observation: this code gives different results for python2 and python3
# because of the behaviour for the division operator
print(3 / 5.0)
print(3 / 5)

# for compatibility, make sure to use the follow statement
from __future__ import division
print(3 / 5.0)
print(3 / 5)

Data Strutures


In [ ]:
countries = ['Portugal','Spain','United Kingdom']
print(countries)

Exercise 0.1

Use L[i:j] to return the countries in the Iberian Peninsula.


In [ ]:
countries[0:2]

Loops and Indentation


In [ ]:
i = 2
while i < 10:
    print(i)
    i += 2

In [ ]:
for i in range(2,10,2):
    print(i)

In [ ]:
a=1
while a <= 3:
    print(a)
    a += 1

Exercise 0.2

Can you then predict the output of the following code?:


In [ ]:
a=1
while a <= 3:
    print(a)
a += 1

Control Flow


In [ ]:
hour = 16
if hour < 12:
    print('Good morning!')
elif hour >= 12 and hour < 20:
    print('Good afternoon!')
else:
    print('Good evening!')

Functions


In [ ]:
def greet(hour):
    if hour < 12:
        print('Good morning!')
    elif hour >= 12 and hour < 20:
        print('Good afternoon!')
    else:
        print('Good evening!')

Exercise 0.3

Note that the previous code allows the hour to be less than 0 or more than 24. Change the code in order to indicate that the hour given as input is invalid. Your output should be something like:

greet(50) Invalid hour: it should be between 0 and 24. greet(-5) Invalid hour: it should be between 0 and 24.


In [ ]:
greet(50)

In [ ]:
greet(-5)

Profiling


In [ ]:
%prun greet(22)

Debugging in Python


In [ ]:
def greet2(hour):
    if hour < 12:
        print('Good morning!')
    elif hour >= 12 and hour < 20:
        print('Good afternoon!')
    else:
        import pdb; pdb.set_trace()
        print('Good evening!')

In [ ]:
# try: greet2(22)

Exceptions

for a complete list of built-in exceptions, see http://docs.python.org/2/library/exceptions.html


In [ ]:
raise ValueError("Invalid input value.")

In [ ]:
while True:
    try:
        x = int(input("Please enter a number: "))
        break
    except ValueError:
        print("Oops! That was no valid number. Try again...")

Extending basic Functionalities with Modules


In [ ]:
import numpy as np
np.var?

In [ ]:
np.random.normal?

Organizing your Code with your own modules

See details in guide

Matplotlib – Plotting in Python


In [ ]:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline 
X = np.linspace(-4, 4, 1000)
plt.plot(X, X**2*np.cos(X**2))
plt.savefig("simple.pdf")

Exercise 0.5

Try running the following on Jupyter, which will introduce you to some of the basic numeric and plotting operations.


In [ ]:
# This will import the numpy library
# and give it the np abbreviation
import numpy as np
# This will import the plotting library
import matplotlib.pyplot as plt
# Linspace will return 1000 points,
# evenly spaced between -4 and +4
X = np.linspace(-4, 4, 1000)
# Y[i] = X[i]**2
Y = X**2
# Plot using a red line ('r')
plt.plot(X, Y, 'r')
# arange returns integers ranging from -4 to +4
# (the upper argument is excluded!)
Ints = np.arange(-4,5)
# We plot these on top of the previous plot
# using blue circles (o means a little circle)
plt.plot(Ints, Ints**2, 'bo')
# You may notice that the plot is tight around the line
# Set the display limits to see better
plt.xlim(-4.5,4.5)
plt.ylim(-1,17)
plt.show()

In [ ]:
import matplotlib.pyplot as plt
import numpy as np
X = np.linspace(0, 4 * np.pi, 1000)
C = np.cos(X)
S = np.sin(X)
plt.plot(X, C)
plt.plot(X, S)
plt.show()

Exercise 0.6

Run the following example and lookup the ptp function/method (use the ? functionality in Jupyter)


In [ ]:
A = np.arange(100)
# These two lines do exactly the same thing
print(np.mean(A))
print(A.mean())

In [ ]:
np.ptp?

Exercise 0.7

Consider the following approximation to compute an integral

\begin{equation*} \int_0^1 f(x) dx \approx \sum_{i=0}^{999} \frac{f(i/1000)}{1000} \end{equation*}

Use numpy to implement this for $f(x) = x^2$. You should not need to use any loops. Note that integer division in Python 2.x returns the floor division (use floats – e.g. 5.0/2.0 – to obtain rationals). The exact value is 1/3. How close is the approximation?


In [ ]:
def f(x):
    return(x**2)

sum([f(x*1./1000)/1000 for x in range(0,1000)])

Exercise 0.8

In the rest of the school we will represent both matrices and vectors as numpy arrays. You can create arrays in different ways, one possible way is to create an array of zeros.


In [ ]:
import numpy as np
m = 3
n = 2
a = np.zeros([m,n])
print(a)

You can check the shape and the data type of your array using the following commands:


In [ ]:
print(a.shape)
print(a.dtype.name)

This shows you that “a” is an 3*2 array of type float64. By default, arrays contain 64 bit6 floating point numbers. You can specify the particular array type by using the keyword dtype.


In [ ]:
a = np.zeros([m,n],dtype=int)
print(a.dtype)

You can also create arrays from lists of numbers:


In [ ]:
a = np.array([[2,3],[3,4]])
print(a)

Exercise 0.9

You can multiply two matrices by looping over both indexes and multiplying the individual entries.


In [ ]:
a = np.array([[2,3],[3,4]])
b = np.array([[1,1],[1,1]])
a_dim1, a_dim2 = a.shape
b_dim1, b_dim2 = b.shape
c = np.zeros([a_dim1,b_dim2])
for i in range(a_dim1):
    for j in range(b_dim2):
        for k in range(a_dim2):
            c[i,j] += a[i,k]*b[k,j]
print(c)

This is, however, cumbersome and inefficient. Numpy supports matrix multiplication with the dot function:


In [ ]:
d = np.dot(a,b)
print(d)

In [ ]:
a = np.array([1,2])
b = np.array([1,1])
np.dot(a,b)

In [ ]:
np.outer(a,b)

In [ ]:
I = np.eye(2)
x = np.array([2.3, 3.4])
print(I)
print(np.dot(I,x))

In [ ]:
A = np.array([ [1, 2], [3, 4] ])
print(A)
print(A.T)

In [ ]: