Introduction to Python - A Python Tutorial

A Tutorial by Jacob Gerace

Why Python?

  1. Clean syntax
  2. The same code can run on all Operating Systems
  3. Extensive first and third party libraries (of particular note for our purposes is NumPy)

Markdown Sidenote

  • This text is written in a Markdown block. Markdown is straightforward way to format writeups in Jupyter, but I won't cover it here for the sake of brevity.
  • See if you can use Markdown in your next homework, here's a link that explains the formatting: https://daringfireball.net/projects/markdown/syntax .
  • You can also look at existing Markdown examples (i.e. this worksheet) and emulate the style. Double click a Markdown box in Jupyter to show the code.

LaTeX Sidenote

  • LaTeX (pronounced "La-tech") is a language itself used widely to write documents with symbolic math
  • When you add a mathematical formula to these markdown blocks, the math is in LaTeX.
  • Ex from class: $$V \frac{dC}{dt} = u(t) - Q C(t)$$
  • A good resource: https://en.wikibooks.org/wiki/LaTeX/Mathematics

What I hope you'll get out of this tutorial:

  • The feeling that you'll "know where to start" when you see python code in lecture, or when you need to write python for an assignment.
  • (You won't be a python expert after one hour)
  • Basics to variables, lists, conditionals, functions, loops, and the numpy package.
  • Resources to look further

Python Basics

Variable Basics

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)

More Complicated Data Types

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. 

Basic Things to do with Variables. Especially Floats.

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 let's look at numpy, which makes things easier.

Conditionals in Python

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.

Functions in Python

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( string ):
    print(string)
   
   #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())

Loops in Python

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)

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

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

Additional Resources

In [ ]: