In [1]:
# "Magic" to allow plotting and math automatically below.
# Don't forget to execute this cell!
%pylab inline
Populating the interactive namespace from numpy and matplotlib

numpy allows math, matplotlib allows plotting.

Symbols are the building blocks

Mathematical Expression Python Expression
Numbers $2$, $2,000$, $2\times10^9$ 2, 2000, 2e9
Operators $a + b$ a + b
$a - b$ a - b
$a \times b$ a * b
$\frac{a}{b}$ a / b
$a^b$ a ** b
Parentheses $2(a+b)$ 2*(a+b)
Variables $a$, $b$, $\alpha$, $\beta$ a, b, alpha, beta
Functions $f_1(x)$ f1(x)

Basic Math

You can do arithmetic with Python

Use Python as calculator:

In [2]:
print (3+2)
print (2**3)
print (3/5)
print ( (3+5)-(2-1))
5
8
0.6
7
In [3]:
(1 + 2) * (34 - 2) / 10
Out[3]:
9.6
In [4]:
10000 / (3 * 8 * 30)
Out[4]:
13.88888888888889

Exponentiation is done with **

In [5]:
2**3
Out[5]:
8
In [6]:
2**0.5
Out[6]:
1.4142135623730951

Not very exciting, not really coding; Writing code requires abstraction, so that code can be reused in different circumstances

Challenge

If I had to walk 10000 miles, and I could walk 3 miles an hour for 8 hours a day, how many months would it take me?

Variables

Variables are placeholders for data; Variables can hold a different value at different executions of the code.

In [7]:
x = 2
y = 3
my_num = 99
my_string = "luft ballons" # A "string" is a piece of text

You can print out the value of a variable

In [8]:
print(x)
print(my_string)
print (my_num, my_string)
2
luft ballons
99 luft ballons

Variables can be reassigned.

In [9]:
x = 2
print(x)
x = 3
print(x)
2
3

Note that the equals sign (=) is an assignment operator: it says "I want to call the thing on the right by the name on the left"

What else can we do with variables? Variables can be used to manipulate data

In [10]:
x + y
Out[10]:
6
In [11]:
z = x + y
print (z)
6

Note: When you write x=7 you are making a statement. When you operate on your variables you are writing expressions. ipython notebook evaluates each expression and then prints that on the screen. But that is not typical Python code behavior.

We use variables when we don't know ahead of time the value of something. This is almost always the case when we write code. Variables allow us to make code general and applicable to many different situations. When we use a variable in our program we say to the computer: when this program executes, this variable x will have some value, (the value may depend on user input or on a measurement of the temperature or on the values of other variables in the program). I don't know what that value will be, but whater it is do the following.

Functions

Functions are pieces of code that you can reuse by calling them

In [12]:
def addtwo(myVar):
    print(myVar+2)
    

myVar is the name of the parameter that you pass to the function. When you call that function, you can pass any (numeric) value to the function and it will be stored in the name myVar within the function. Note: myVar is only defined within this function

Note: myVar is only defined within this function

In [13]:
print(myVar)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-13-11d180c4804a> in <module>()
----> 1 print(myVar)

NameError: name 'myVar' is not defined
In [14]:
addtwo(5)
7

Challenge:

write a function which takes in two parameters and prints their sum to the screen. Now call this function, passing necessary parameters and check that it works.

Great! We can write functions that do things! But how would you save the result of a computation (ie output of a function) for future use in your code? try:

In [15]:
y = addtwo(2)
print(y)
4
None

'Return'

Functions can 'return' a value

In [16]:
def addtwo(myVar):
    return (myVar+2)

what do you think the following 2 expressions will produce?

In [17]:
y = addtwo(5)
print(y)
7
In [18]:
y = addtwo(x)
print(y)
5
In [19]:
y = addtwo(x)/2
print (y)
y = addtwo( addtwo(x)/2)
print(y)
2.5
4.5

Python built-in functions:

Now that we know what functions are, we can understand better some of the things we have already done: eg: print() is a function that is part of an included library (of functions) in Python

Other functions

In [20]:
cos(x)
Out[20]:
-0.98999249660044542
In [21]:
cos(2*pi*x)
Out[21]:
1.0
In [22]:
floor(2.56)
Out[22]:
2.0
In [23]:
sqrt(addtwo(floor(cos(x))))
Out[23]:
1.0

Function challenge

  • write a function called remainder that returns the remainder of x/y
  • a function that prints the quotient and returns the remainder

Functions on lists:

We saw functions last class when we made our plot:

In [24]:
plot ([1,2,3,4], [7,-1,0,-5])
Out[24]:
[<matplotlib.lines.Line2D at 0x7f13a404fe10>]

From homework:

In [25]:
plot([1,2,3], [1,2,3], 'go-', label='line 1', linewidth=2)
plot([1,2,3], [2, 3, 4], 'bo-', label='line 2', linewidth=2)

plot([1,2,3], [2, 3, 4], color='b', marker='o', label='line 2', linewidth=4)
Out[25]:
[<matplotlib.lines.Line2D at 0x7f139ffc0da0>]

plot() is a function that takes in several variables. There are a few differences from what we've done so far:

  • variables are of different type than just simple scalars; ie [1,2,3] => these are LISTS (or arrays)
  • the arguments after the 1st two are optional and specified by name. These are called keyword arguments. They are confusing, we'll talk about then later. For now, just learn to use them in plot()

Lists

Lists are create with square brackets

In [26]:
myList = [1, 2]
myList
Out[26]:
[1, 2]
In [27]:
print(myList)
[1, 2]

Functions that are specific to Lists and operate on lists (called methods) sometimes require the list.function() syntax. We will learn about this more when we study objects and object oriented programming. But for now:

In [28]:
l = []
l.append(1)
l.append(2)
l
Out[28]:
[1, 2]
In [29]:
nameList=["yongsun", 'janet', 'aleksandra', 'tayshana']
print (nameList)
nameList.append("Laura")
print (nameList)
['yongsun', 'janet', 'aleksandra', 'tayshana']
['yongsun', 'janet', 'aleksandra', 'tayshana', 'Laura']
In [30]:
nameList[3] #returns the 3 rd element from the list
Out[30]:
'tayshana'

is this what you expected? write an expression using our nameList that returns "youngsun"

In [31]:
nameList[0]
Out[31]:
'yongsun'

Does the list still include tayshana or has it been removed? Try it out. Raise your hand if you think Tayshana is still in the list.

In [32]:
nameList.remove('tayshana')
nameList
Out[32]:
['yongsun', 'janet', 'aleksandra', 'Laura']

Plotting with Lists again (review)

In Python, the plot function takes two lists as arguments: a list of x-coordinates, and a list of y-coordinates. That is the bare minimum you need to plot.

Practice

Write code to plot [0, 1,2,3] vs [0,2,1,3]

You can add keyword arguments to change the appearance of a plot. You can plot multiple data sets on the same plot.

In [33]:
xList = [1,2,3]
yList1 = [1,2,3]
yList2 = [2,3,4]
plot(xList, yList1, 'gx-', label='line 1', linewidth=2)
plot(xList, yList2, 'ro-', label='line 2', linewidth=2)
Out[33]:
[<matplotlib.lines.Line2D at 0x7f139ffde2b0>]
In [34]:
xs = [0, 1, 2, 3]
ys = [0, 2, 1, 3]
plot(xs, ys)

ys2 = [0.1, 1, 1.5, 0.5]
plot(xs, ys2)
Out[34]:
[<matplotlib.lines.Line2D at 0x7f139ff8f668>]

Arrays

An array is a like a list, but for just numbers. It allows you to do math on the whole array.

In [35]:
xs = array([0, 1, 2, 3])
ys = array([0, 2, 1, 3])
plot(xs, ys)

ys2 = ys - xs
plot(xs, ys2)
Out[35]:
[<matplotlib.lines.Line2D at 0x7f139f75ca20>]
In [36]:
xs = array([0, 1, 2, 3])
ys = array([0, 2, 1, 3])
plot(xs, ys**2)
Out[36]:
[<matplotlib.lines.Line2D at 0x7f139df30e80>]

Creating arrays

In [37]:
xs = linspace(-5, 5, 200) # Create an array from -5 to 5, with 200 elements
ys = exp(-xs**2)
plot(xs, ys)
Out[37]:
[<matplotlib.lines.Line2D at 0x7f139df169b0>]
In [38]:
xs = linspace(-4, 4, 200) # Create an array from -4 to 4, with 200 elements
ys = exp(-xs**2)
plot(xs, ys, label="A Gaussian plot", linewidth=3, color='r')
title("Look, a Gaussian!")
xlabel("The x axis")
ylabel("The y axis")
legend() # Uses the labels from each plot expression
Out[38]:
<matplotlib.legend.Legend at 0x7f139de81898>

functions operating on arrays:

In [39]:
sum(xs)
Out[39]:
2.8421709430404007e-14

Subarrays

In [40]:
z = xs[0:10]

How many elements does z have?

In [41]:
print(z)
[-4.         -3.95979899 -3.91959799 -3.87939698 -3.83919598 -3.79899497
 -3.75879397 -3.71859296 -3.67839196 -3.63819095]
In [42]:
print (len(z))
10

2D arrays

In [43]:
mat = array([[1,2,3],[10,11,12]])
print(mat)
[[ 1  2  3]
 [10 11 12]]
In [44]:
myRow = mat[0, :]
print(myRow)
[1 2 3]

Now write code to print the 2nd column

In [45]:
myCol = mat[:, 1]
print(myCol)
[ 2 11]
In [46]:
im = loadtxt(fname='data/sizeCalibration.txt')
In [47]:
imshow(im)
Out[47]:
<matplotlib.image.AxesImage at 0x7f1397f57780>
In [48]:
slice = im[:,1];
print(len(slice))
1050
In [49]:
plot(range(0,1050), slice)
Out[49]:
[<matplotlib.lines.Line2D at 0x7f1397f7c438>]
In [50]:
print(max(slice))
print (min(slice))
255.0
18.0