Python is an interpreted language
That means it responds to things you type in and it is waiting for you to type things. It excecutes instructions on the CPU based on what you type.
Interpreted languages are usually slower than compiled languages.
A compiled language produces CPU runable code from a series of instructions. You then run the code. Compilers are designed to make efficient code.
However, python does compile its functions. One a function is loaded into python, a compiled version can be made that then can be run later on.
Python is still usually slower than something compiled like C, C++ or Fortran.
If you have a computationally intensive task, you could link from python to a library compiled code that is originally written in C or another language.
If you are an engineer or a biologist you might wind up using matlab (which is not free) instead of python. Many matlab-like routines have been ported into python.
You need to have a python distribution that contains packages numpy, matplotlib.
I like to use jupyter notebooks as you can easily rerun code, embed figures and use markdown with pretty latex equations.
I encourage you download a python distribution, like the free ones available as anaconda or canopy that comes with notebooks.
I usually launch jupyter notebooks from a command line but you can also use the ap that comes with various distributions.
Why work in a browswer? The data you are working on need not be on your computer. The code that you run need not be run on your computer. The code you run need not be developed for every type of operating system if you run your code on special computers that are not your computer.
What needs to be on your computer? A way for you to look at the code output.
Browsers are optmimized to display things efficiently for your eyes.
Jupyter notebooks are good for running and rerunning code as you develop it. They can be used to keep a record of your projects. You can embed your equations and figures in the project.
Can you collaborate in a jupyter notebook? Not yet: There are some non-free platforms under development. Maybe by next year it might become possible to simultaneously edit a notebook with a friend on-line (on a free platform).
For large projects you need to write subroutines in separate files. You could then load them into a notebook to run.
code and markdown.
Markdown lets you make nice TeX equations!
$x=1$
$$ \sum_{x=1}^\infty z^\alpha $$Lists
Html bold!
nice code:
more nice code
# showing some variable assignment + manipulation
x=1
x=x+1
print(x)
x+=1
print(x)
x
?x
The most irritating difference is in the print function.
Thankfully many packages have been upgraded to 3.x
sin(3)
# showing how to import numpy
import numpy as np
x=1.0
np.sin(x)
np.pi #pi!
# An example of importing a function
from numpy import exp
# we don't need to use np.exp()
exp(x)
import os # operating system
os.getcwd()
# multiple variables at once!
x=1
y=2
x,y = y,x
x,y # this is a tuple
# define a simple function
def f(x):
y = (x+7)**2
return y
# print for python 3.x uses ()
print(f(8.0))
# functions can take more than one argument and
# can return more than one thing as a tuple
def g(x,y):
if (x >0):
return 0,x
else:
return 1,y
a,b = g(1,2)
print('g(1,2)=',a,b)
a,b = g(-1,2)
print('g(-1,2)=',a,b)
indents can be 4 spaces or a tab but you can't mix the types of indents
Indents are a pain.
# lets screw up some indents
def h(x):
return x**1.5
# lets screw up some indents
def h(x):
return x**1.5
h(2) # this works but the red tells you there is a problem
# twofunctions that are identical except for indents
def h1():
ssum = 0
for i in range(3):
ssum += i;
for j in range(3):
ssum +=j
print(ssum)
def h2():
ssum = 0
for i in range(3):
ssum += i;
for j in range(3):
ssum += j;
print(ssum)
h1() # these do not give the same answer
h2()
sum = 1 # do not run this! sum is green and that means it has another use
lambda #
np =3 # don't run this if you want to use numpy as np!
str # don't run this if you want to use str to convert something to a string
# examples of string manipulation
str1 = 'Pan'
str2 = '_is_a_moon'
zzz = str1 + str2
print(zzz)
zzz[0] # indexing a string
n = len(zzz) #length of string or array or list
print(n)
str1 = "Pan"
str3="Pan'
you can use single quotes or double quotes for string constants but you need to start and stop the string with the same symbol
zzz[14] # outside of allocated memory
zzz[-1] # last thing in list
zzz[-4:] # last four things in the list
zzz[0:3] # first 3 things in the list
zzz = 'Pan_is_a_moon'
n = len(zzz) # length of the string
for i in range(n):
print(i,zzz[i]) # useful for making for loops!
# notice that above the printout started with index 0
# lists
mylist = [1,2,3,4]
for i in mylist:
print(i)
atup = ('a', 'bc', 'cd', 4) # a tuple
for i in atup:
print (i)
mylist = ['A', 'b', 1, '17',17.5]
for i in mylist:
print(type(i))
x = np.array([1.0,2,3,4]) # an array is different than a list
x[-1] # the last object in the array
y=[6,7,8,9]
print(y)
y[2] = [1,2] # if y is a list you can set an element into to become another list
## Question: what is going to happen?
print(y)
x = np.array([1.0,2,3,4]) # an array is different than a list
## Question: what is going to happen?
x[2] = [1,2]
# Answer: you cannot do this if x is an array rather than a list (you get an error)
## Question: what will happen?
x[2]='a'
# Answer: you cannot do this if x is an array (you get an error)
x = np.array([1.0,2,3,4])
print(x)
y=x # y just points to the x array
print(y)
x[2]=10.0
## Question: what will happen?
print(y)
# Answer: if you change an element of x, then that element in y will also change
x = np.array([1.0,2,3,4])
z = np.copy(x)
x[2]=10
print(x)
print(z)
# note: copy makes an array
# to make a list from an array use
# from numpy import ndarray
# ndarray.tolist(np.array(alist))
z=1 # variables are passed by numbers
y=z
z=2
## Question: what will happen?
print(y)
## Answer: y is not changed
def addone(x): # passes by number if x is a variable!
x+= 1 # nothing is returned
## Question: if a variable x is passed will it change?
## Question: if an array x is passed will it change?
x = 1
addone(x)
print(x)
# Answer: variable x is not changed
x = np.array([1,2])
addone(x)
# Question: will the array x change?
print(x) # Answer: array x is changed!
def f(x):
y = x+7 + b_var # b_var is not defined locally, assumed to be a global variable
return y
# Question: what will happen?
f(1)
## Answer: b_var was not defined locally and we had not
# defined a variable called b_var globally
# the variable is not defined.
b_var=1 # defined globally
## Question: Now what will happen?
print(f(1))
# Answer: we defined a global variable b_var which is used within the routine f()
b_var=1
def f(x):
b_var=2 # defined locally
y = x+7 + b_var
return y
print(f(1))
## Question: is b_var changed?
print(b_var) # Answer, no b_var is not changed! (before it was 1)
# Answer: Locally defined variables overide those that are defined globally
def f(x):
x = 2
return x**2
## Question: what does this function do?
print(f(2))
print(f(3))
# Answer: locally defined variables overide the ones that
# are passed as arguments to a function.
numpy routines: linspace, arange, and zeros
t = np.arange(0,1,0.1) # arguments: start, stop-increment, increment
t
t = np.linspace(0,1,101) # allocating a nice long vector
# arguments: start, stop, number of elements
t
t = np.linspace(0,1,11)
y=np.sin(6.0*t) # on the whole array at once!
It is faster to do arithmetic and functions of whole arrays than to loop over the array via each index.
Many numpy routines will work on arrays. Many math routines will not.
# this is slower but does the same thing
y = np.zeros(len(t)) # allocate
for i in range(len(t)): # loop for each index of the array
y[i] = np.sin(6*t[i]) # compute for each element of the array
# let the notebook know you want plots in the notebook
%matplotlib inline
# load in the plotting package!
import matplotlib.pyplot as plt
plt.xlabel("time", fontsize=22) # a nice plot with labels
plt.ylabel("sine!", fontsize=22)
plt.plot(t,y, 'ro') # red points
plt.plot(t,y, 'k-') # black line
z = np.zeros(10) # another handy way to allocate an array
z
It is often very useful to be able to add to an array.
This requires allocating more space for it.
z=np.arange(0,3,0.2)
bunch_of_zeros=np.zeros(10)
combined_array = np.append(z,bunch_of_zeros)
print(combined_array)
def using_if(x): # example of an if statement
if (x == 3):
print("x is equal to 3")
else:
print("x is not equal to 3")
using_if(2)
using_if(3)