Python Tutorial #2

A Tutorial by Jacob Gerace

Conditionals in Python

In [24]:
#Sometimes you want to execute code only in certain circumstances. 

#Change answer and see what code is executed:
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
snowy = True
day = "Monday"

#How long does it take me to get to class in the morning?

if (snowy == False) and (day != "Monday"):
    #and is boolean and. True only if both are true. False otherwise
    time = 7
elif (snowy == True) and (day == "Monday"):
    time = 11
elif (rainy == True) or (day == "Monday"):
    time = 9
    
print("It takes me %d minutes" %(time))
    
#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.
This is the answer to the ultimate question
This print statement is run no matter what because it is not indented!
It takes me 11 minutes

Functions in Python

In [15]:
#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( string ):
    print(string)
   
   #End with the "return" keyword
    return

#Your functions can return data if you so choose
def step(x):
    if (x < 0):
        return -1
    elif (x > 0):
        return 1

#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!

print(step(-1))
print(step(1))

#what happens for x = 0?
print(step(0))

#Python automatically adds in a "return none" statement if you are missing one. 
#If you see "none" make sure your program can work with that!


#Fix the return none issue
def step_v2(x):
    if (x < 0):
        return -1
    elif (x >= 0):
        return 1
    
print(step_v2(0))
-1
1
None
1

Numpy - "The Fundamental Package for Scientific Computing with Python"

In [16]:
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.

#What about multi-dimensional arrays? Matrices!

#You just nest lists within lists! 
A = np.array( [[1,2,3], [4,5,6], [7,8,9]] )
B = np.array( [[1,1,1], [2,2,2], [3,3,3]] )

#Then matrix multlication
C = np.matmul(A,B)
 
print(C)

#Or determinants:
print(np.linalg.det(A))


#Now, let's use numpy for something essential for you: Numeric Integration

#Define the function you want to integrate....
#dy/dt = t:
def deriv(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(deriv,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)
plt.title("y = (1/2)t^2")
#Very similar to MATLAB!
[1 2 3]
1
[10 10 10]
[-8 -6 -4]
[ 9 16 21]
[ 0.11111111  0.25        0.42857143]
[[14 14 14]
 [32 32 32]
 [50 50 50]]
-9.51619735393e-16
Out[16]:
<matplotlib.text.Text at 0x242d63ab438>

Additional Resources