In [ ]:
#A variable stores a piece of data and gives it a name
#syntax of the form:
#variable_name = variable_value
#What are some types of variables you will need to use?
In [ ]:
#Lists
#Defining a list and printing is very simple:
prices = [10, 20, 30, 40, 50]
print(prices)
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. What does this do?
result = 5 % 2
#What are some other math functions you would like to do with floats?
In [ ]:
#Sometimes you want to execute code only in certain circumstances. We saw this on HW1.
#The basic syntax is:
#if boolean_statement_1:
# _code to do if 1 is true_
#elif boolean_statement_2:
# _code to do if 2 is true_
#else:
# _code to do in all other cases_
#A boolean statement is something that can be True or False. Named after mathematician George boole. (5 < 3) is an
#example, and in this case evaluates to False.
#The tabs are mandatory. Let's do some more examples
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
#What if we want to compute something and return the result? How would you write that return statement?
In [ ]:
#Repeat code until a conditional statement (or boolean expression, same thing!) ends the loop
#Let's try printing a list
fib = [1, 1, 2, 3, 5, 8]
#Most of your loops can be written in the following way. Before we get to this, we'll go over two less neat ways to write
#the same thing
for e in fib:
print(e)
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
#What are other things you would like to do with these arrays?
#If we don't get to it, be sure to look at the notes once uploaded for Numeric ODE Integration!
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 [ ]: