In [ ]:
#A variable stores a piece of data and gives it a name
answer = 42
#answer contained an integer because we gave it an integer!
is_it_tuesday = True
is_it_wednesday = False
#these both are 'booleans' or true/false values
pi_approx = 3.1415
#This will be a floating point number, or a number containing digits after the decimal point
my_name = "Jacob"
#This is a string datatype, the name coming from a string of characters
#Data doesn't have to be a singular unit
#p.s., we can print all of these with a print command. For Example:
print(answer)
print(pi_approx)
In [ ]:
#What if we want to store many integers? We need a list!
prices = [10, 20, 30, 40, 50]
#This is a way to define a list in place. We can also make an empty list and add to it.
colors = []
colors.append("Green")
colors.append("Blue")
colors.append("Red")
print(colors)
#We can also add unlike data to a list
prices.append("Sixty")
#As an exercise, look up lists in python and find out how to add in the middle of a list!
print(prices)
#We can access a specific element of a list too:
print(colors[0])
print(colors[2])
#Notice here how the first element of the list is index 0, not 1!
#Languages like MATLAB are 1 indexed, be careful!
#In addition to lists, there are tuples
#Tuples behave very similarly to lists except that you can't change them after you make them
#An empty Tuple isn't very useful:
empty_tuple = ()
#Nor is a tuple with just one value:
one_tuple = ("first",)
#But tuples with many values are useful:
rosa_parks_info = ("Rosa", "Parks", 1913, "February", 4)
#You can access tuples just like lists
print(rosa_parks_info[0] + " " + rosa_parks_info[1])
#You cannot modify existing tuples, but you can make new tuples that extend the information.
#I expect Tuples to come up less than lists. So we'll just leave it at that.
In [ ]:
float1 = 5.75
float2 = 2.25
#Addition, subtraction, multiplication, division are as you expect
print(float1 + float2)
print(float1 - float2)
print(float1 * float2)
print(float1 / float2)
#Here's an interesting one that showed up in your first homework. Modulus. The remainder of division:
print(5 % 2)
#Just about every standard math function on a calculator has a python equivalent pre made.
#however, they are from the 'math' package in python. Let's add that package!
import math
print(math.log(float1))
print(math.exp(float2))
print(math.pow(2,5))
# There is a quicker way to write exponents if you want:
print(2.0**5.0)
#Like in MATLAB, you can expand the math to entire lists
list3 = [1, 2, 3, 4, 5]
print(2 * list3)
#There's more you can do with lists in normal python, but we'll save more operations until we get to numpy.
In [ ]:
#Sometimes you want to execute code only in certain circumstances. We saw this on HW1.
#Should be fairly straightforward:
answer = 42
if answer == 42:
print('This is the answer to the ultimate question')
elif answer < 42:
print('This is less than the answer to the ultimate question')
else:
print('This is more than the answer to the ultimate question')
print('This print statement is run no matter what because it is not indented!')
#An if statement is an example of a structure that creates a new block. The block includes all of the code that is
#indented. The indentation (tab character) is imperative. Don't forget it!
#This is normally just good coding style in other languages, but in python it isn't optional
#We can check multiple things at once using boolean operations
rainy = True
day = "Wednesday"
if (rainy == False) and (day != "Tuesday"):
#&& is boolean and, true only if both are true. False otherwise
print("The price for golfing is the full $10")
elif (rainy == True) and (day == "Tuesday"):
print("The price for golfing is reduced to $5!")
elif (rainy == True) or (day == "Tuesday"):
#|| is boolean inclusive or False only if both are false. True otherwise.
print("The price for golfing is reduced to $7.50!")
#You can structure these statements more neatly if you "nest" if statements (put an if statement inside an if statement)
#But this is just for edification.
In [ ]:
#We can separate off code into functions, that can take input and can give output. They serve as black boxes from the
#perspective of the rest of our code
#use the def keyword, and indent because this creates a new block
def print_me( str ):
print(str)
#End with the "return" keyword
return
#Your functions can return data if you so choose
def my_favorite_song( ):
ans = "Amsterdam - Imagine Dragons"
return ans
#call functions by repeating their name, and putting your variable in the parenthesis.
#Your variable need not be named the same thing, but it should be the right type!
text = "I'll take the West train, just by the side of Amsterdam"
print_me(text)
print(my_favorite_song())
In [ ]:
#Repeat code until a conditional statement ends the loop
#Let's try printing a list
fib = [1, 1, 2, 3, 5, 8]
#While loops are the basic type
i = 0
while(i < len(fib)):
print(fib[i])
i = i + 1
#In matlab, to do the same thing you would have the conditional as: counter < (length(fib) + 1)
#This is because matlab starts indexing at 1, and python starts at 0.
#The above type of loop is so common that the 'for' loop is the way to write it faster.
print("Let's try that again")
#This is most similar to for loops in matlab
for i in range(0, len(fib)) :
print(fib[i])
print("One more time:")
#Or you can do so even neater
for e in fib:
print(e)
In [6]:
import numpy as np
#Here, we grab all of the functions and tools from the numpy package and store them in a local variable called np.
#You can call that variable whatever you like, but 'np' is standard.
#numpy has arrays, which function similarly to python lists.
a = np.array([1,2,3])
b = np.array([9,8,7])
#Be careful with syntax. The parentheses and brackets are both required!
print(a)
#Access elements from them just like you would a regular list
print(a[0])
#Element-wise operations are a breeze!
c = a + b
d = a - b
e = a * b
f = a / b
print(c)
print(d)
print(e)
print(f)
#This is different from MATLAB where you add a dot to get element wise operators.
#If you actually do want to do matrix multiplication...
g = np.matmul(np.transpose(a),b)
print(g)
#Now, let's use numpy for something essential for you: Numeric Integration
#Define the function you want to integrate....
def foo(y,t):
return t
#Note this doesn't use y in the return. That is okay, but we need to include it just to satisfy the function we will use.
#Set your initial or boundary condition
IC = 0
#Give the number of points to evaluate the integration
start_time = 0
end_time = 10
num_times = 101
times = np.linspace(start_time, end_time, num_times)
from scipy.integrate import odeint
integrated_func = odeint(foo,IC,times)
#Can we plot the result? You betcha. Just import a new package
%matplotlib inline
import matplotlib.pyplot as plt
from ipywidgets import interact
plt.plot(times, integrated_func)
#Very similar to MATLAB!
Out[6]:
If you still feel VERY lost: Code Academy
If you want a good reference site: Official Python Reference
If you want to learn python robustly: Learn Python the Hard Way
Feel free to contact me at: jgerace (at) nd (dot) edu
In [ ]: