Make sure to have all the required software installed after proceeding. For installation help, please consult the school guide.
In [ ]:
print('Hello World!')
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)
In [ ]:
countries = ['Portugal','Spain','United Kingdom']
print(countries)
In [ ]:
countries[0:2]
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
In [ ]:
a=1
while a <= 3:
print(a)
a += 1
In [ ]:
hour = 16
if hour < 12:
print('Good morning!')
elif hour >= 12 and hour < 20:
print('Good afternoon!')
else:
print('Good evening!')
In [ ]:
def greet(hour):
if hour < 12:
print('Good morning!')
elif hour >= 12 and hour < 20:
print('Good afternoon!')
else:
print('Good evening!')
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)
In [ ]:
%prun greet(22)
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)
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...")
In [ ]:
import numpy as np
np.var?
In [ ]:
np.random.normal?
See details in guide
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")
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()
In [ ]:
A = np.arange(100)
# These two lines do exactly the same thing
print(np.mean(A))
print(A.mean())
In [ ]:
np.ptp?
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)])
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)
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 [ ]: