# "Magic" to allow plotting and math automatically below.
# Don't forget to execute this cell!
%pylab inline
numpy allows math, matplotlib allows plotting.
| 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) |
You can do arithmetic with Python
print (3+2)
print (2**3)
print (3/5)
print ( (3+5)-(2-1))
(1 + 2) * (34 - 2) / 10
10000 / (3 * 8 * 30)
Exponentiation is done with **
2**3
2**0.5
Not very exciting, not really coding; Writing code requires abstraction, so that code can be reused in different circumstances
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 are placeholders for data; Variables can hold a different value at different executions of the code.
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
print(x)
print(my_string)
print (my_num, my_string)
Variables can be reassigned.
x = 2
print(x)
x = 3
print(x)
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
x + y
z = x + y
print (z)
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 are pieces of code that you can reuse by calling them
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
print(myVar)
addtwo(5)
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:
y = addtwo(2)
print(y)
Functions can 'return' a value
def addtwo(myVar):
return (myVar+2)
what do you think the following 2 expressions will produce?
y = addtwo(5)
print(y)
y = addtwo(x)
print(y)
y = addtwo(x)/2
print (y)
y = addtwo( addtwo(x)/2)
print(y)
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
cos(x)
cos(2*pi*x)
floor(2.56)
sqrt(addtwo(floor(cos(x))))
We saw functions last class when we made our plot:
plot ([1,2,3,4], [7,-1,0,-5])
From homework:
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)
plot() is a function that takes in several variables. There are a few differences from what we've done so far:
Lists are create with square brackets
myList = [1, 2]
myList
print(myList)
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:
l = []
l.append(1)
l.append(2)
l
nameList=["yongsun", 'janet', 'aleksandra', 'tayshana']
print (nameList)
nameList.append("Laura")
print (nameList)
nameList[3] #returns the 3 rd element from the list
is this what you expected? write an expression using our nameList that returns "youngsun"
nameList[0]
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.
nameList.remove('tayshana')
nameList
More list functions: https://docs.python.org/2/tutorial/datastructures.html
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.
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.
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)
xs = [0, 1, 2, 3]
ys = [0, 2, 1, 3]
plot(xs, ys)
ys2 = [0.1, 1, 1.5, 0.5]
plot(xs, ys2)
An array is a like a list, but for just numbers. It allows you to do math on the whole array.
xs = array([0, 1, 2, 3])
ys = array([0, 2, 1, 3])
plot(xs, ys)
ys2 = ys - xs
plot(xs, ys2)
xs = array([0, 1, 2, 3])
ys = array([0, 2, 1, 3])
plot(xs, ys**2)
xs = linspace(-5, 5, 200) # Create an array from -5 to 5, with 200 elements
ys = exp(-xs**2)
plot(xs, ys)
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
functions operating on arrays:
sum(xs)
z = xs[0:10]
How many elements does z have?
print(z)
print (len(z))
mat = array([[1,2,3],[10,11,12]])
print(mat)
myRow = mat[0, :]
print(myRow)
Now write code to print the 2nd column
myCol = mat[:, 1]
print(myCol)
im = loadtxt(fname='data/sizeCalibration.txt')
imshow(im)
slice = im[:,1];
print(len(slice))
plot(range(0,1050), slice)
print(max(slice))
print (min(slice))