In this tutorial, we cover some of the basic tools you will need for scientific computing with Python. This follows the Tools section of the SimPEG Tutorials.
This development environment is the Jupyter Notebook.
Shift + Enter
Esc + 00
In this notebook, we cover some basics of:
A notebook containing the following examples is available for you to download and follow along. In the directory where you downloaded the notebook, open up a Jupyter Notebook from a terminal
jupyter notebook
and open tools.ipynb
. A few things to note
Throughout this tutorial, we will show a few tips for working with the notebook.
Python is a high-level interpreted computing language. Here we outline a few of the basics and common trip-ups. For more information and tutorials, check out the <a href="https://www.python.org/doc/"Python Documentation</a>.
In [1]:
# python has /types
print(type(1) == int)
print(type(1.) == float)
print(type(1j) == complex)
type(None)
Out[1]:
In [2]:
# What happens if you add values of different types?
print(1 + 1.)
In [3]:
mylist = [6, 5, 4, 3]
type(mylist)
Out[3]:
In [4]:
# length of a list
len(mylist)
Out[4]:
In [5]:
# python uses zero based indexing
print(mylist[0])
In [6]:
print(mylist[:2]) # counting up
print(mylist[2:]) # starting from
print(mylist[-1]) # going back
In [7]:
n = 10 # try making this larger --> see which is faster
In [8]:
%%time
a = []
for i in range(n): # for loop assignment
a.append(i)
print(a)
In [9]:
%%time
b = [i for i in range(n)] # list comprehension
print(b)
In [10]:
# Enumerateing
mylist = ['Monty', 'Python', 'Flying', 'Circus']
for i, val in enumerate(mylist):
print(i, val)
In [11]:
# Pick a random number between 0 and 100
import numpy as np # n-dimensional array package
number = (100.*np.random.rand(1)).round() # make it an integer
if number > 42:
print('{} is too high'.format(number))
elif number < 42:
print('{} is too low'.format(number))
else:
print('you found the secret to life. {}'.format(number))
In [12]:
def pickAnumber(number):
if number > 42:
print('{} is too high'.format(number))
return False
elif number < 42:
print('{} is too low'.format(number))
return False
else:
print('you found the secret to life. {}'.format(number))
return True
In [13]:
print(pickAnumber(10))
In [14]:
import numpy as np
In [15]:
a = np.array(1) # scalar
print(a.shape)
b = np.array([1]) # vector
print(b.shape)
c = np.array([[1]]) # array
print(c.shape)
In [16]:
# vectors
v = np.random.rand(10)
a = v.T * v
print(a.shape)
In [17]:
b = v.dot(v)
b.shape
Out[17]:
In [18]:
# arrays
w = np.random.rand(10,1)
w.shape
Out[18]:
In [19]:
M = np.random.rand(10,10)
In [20]:
M*w
Out[20]:
In [ ]: