Download Introduction to Python Programming Nolan Matthews

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Introduction to
Python Programming
Nolan Matthews
What is Python and why use it?
From Wiki:
○ High-level, widely used programming
language.
○
Emphasis on code readability, and
intended to enable clear programs on
small and large scale.
○
Free and open-sourced.
Pros/Cons to using Python
Pros:
-Easy to read/write
-Extremely popular
(and growing)
-Already ‘infrastructure’
for scientific analysis.
Cons:
-Slower than lower-level
languages (C,C++,..)
-Certain design restrictions
(I personally don’t know
much about this…)
Some basics..
-To start the python interpreter (where you can run code) in
the terminal type:
$python
-You are now within the python environment.
>>>print(“Hello World!”)
Hello World!
-To leave the python environment type:
>>>exit()
Some more basics..
The interpreter allows you to test commands on the fly.
However, if you want to run a script that is within your local
directory type:
$python test_script.py
where test_script.py is code written in a file of your favorite
text editor. (Must have prefix .py)
(Example helloworld.py)
Even more basics...
Here’s some basic
examples:
>>>local_var=17
>>>print(local_var)
17
>>>local_var*2
34
>>>local_var/3
5
Note that int/int == int
>>>local_var/3.0
5.666666667
>>>type(local_var)
‘int’
>>>type(3.0)
‘float’
Loops
Logical Operators
>>>a=3
>>>for i in range(5):
>>>a==3
>>>
True
print(i)
>>>a!=3
>>>N=10
False
>>>while j <= N:
>>>
print(j)
>>>
j+=1
Control Statements
if a==3:
print(‘A equals 3’)
elif a==2:
print(‘A equals 2’)
else:
print(‘A does not =equal 2 or 3’)
Defining functions
In a file named counter.py
def counter(N):
#define function names/inputs
i=0
#initialize index
while i <=N:
#begin while loop
print(i)
#prints out iteration number
i+=1
#adds 1 to i (eqvil. i = i+1)
counter(10)
Notice syntax used in loops! Controlled by indentation…
$python counter.py
What if we want to force N to be an integer?
Defining Functions (cont…)
In many cases you want a function to output a parameter
based on input parameters. Here is a simple example:
def addone(x):
return x+1
y=addone(4)
print(y)
#Returns the value of x+1
#Assigns addone(4) to local var. y
Defining Functions (cont…)
In many cases you want a function to output a parameter
based on input parameters. Here is a simple example:
def addone(x):
return x+1
y=addone(4)
print(y)
TASK: Write a function that takes
in two inputs ‘x’ and ‘c’ and
outputs x^(3/2) + c
Working with Strings/Lists
>>>basket=[“apple”,”banana”,”orange”,”pear”]
>>>for fruits in basket:
#Iterates through ‘basket’
>>>
#Prints out current element in iteration
print(fruits)
Working with Strings/Lists
>>>basket=[“apple”,”banana”,”orange”,”pear”]
>>>for fruits in basket:
#Iterates through ‘basket’
>>>
#Prints out current element in iteration
print(fruits)
-Note that this is equivalent to the more complex method generally used,
>>>for i in range(len(basket)): #Iterates through index number
>>>
print(basket[i])
#Calls specific element of ‘basket’ at index ‘i’
Working with Strings/Lists
>>>basket=[“apple”,”banana”,”orange”,”pear”]
>>>for fruits in basket:
#Iterates through ‘basket’
>>>
#Prints out current element in iteration
print(fruits)
-Note that this is equivalent to the more complex method generally used,
>>>for i in range(len(basket)): #Iterates through index number
>>>
print(basket[i])
#Calls specific element of ‘basket’ at index ‘i’
-There are many list methods which can be utilized in an OOP way.
>>>basket.append(“lemon”) #Adds an element to the end
>>>basket.remove(“orange”) #Removes elements == orange
>>>print(basket)
Importing Packages (“libraries”)
-Similar to C++, python has a lot of pre-built
modules for widely varying tasks. The most
commonly used are the NumPy, SciPy, and
MatPlotLib packages.
NumPy→ Numerical Package.
SciPy→ Scientific Package
MatPlotLib → Graphing/plotting package.
Using Packages/Modules
To import a module:
>>>import numpy
#imports numpy module
>>>numpy.version.version #checks version
>>>import numpy as np #imports under different call
>>>np.sqrt(4)
#mathematical functions..
>>>np.sqrt(6)
#notice ‘int’ to ‘float’ (depends
on version)
NumPy Array Handling
>>>array=np.arange(10)
>>>help(np.arange)
>>>print(array)
>>>print(array[5:8])
>>>print(array[5:])
>>>print(array/2)
>>>array[3] = 15
>>>print array
TASK: Write a function
that takes in an array of
numbers and returns an
array which contains only
the even numbers.
HINTS: % and np.delete
Plotting using MatPlotLib (MPL)
>>>from matplotlib import pyplot as plt
>>>import numpy as np
>>>x=np.arange(0,100)
#Set up X/Y pts.
>>>y=2*x
>>>plt.plot(x,y)
#Put on figure
>>>plt.show()
#Display Figure
Extremely Simple!
>>>help(plt.plot)
Interacting with MPL figures
-We will look at an example from the matplotlib
website (slightly modified) to some of the
capabilities of MPL figures using the
integral_demo.py script
$python integral_demo.py
Interacting w/ MPL figures (cont..)
TASK: Modify the integral_demo.py script to
implement the following steps:
-Include labels for the X/Y axes and also a title.
-Remove the x and y text at the corners of the graph.
-Below the LaTeX text include a line (using ‘LaTeX’ font)
that describes what f(x) is. Be sure that it is properly
displayed on the graph.
-Force the line color of f(x) to be red.
Working with SciPy
-SciPy contains routines that often show up in
scientific work (e.g. numerical integrals,
solution of diff. eq’s, optimization..)
-Contains broad range of functions. Here we
will focus on the optimization package.
Curve Fitting in Python
-Lets first create some simulated data. Let’s do
this in a file called cfitting.py
>>>mu,sigma,numPts=0,2.0,1000
>>>x=np.arange(numPts)
>>>help(np.random.normal)
>>>y=x+np.random.normal(mu,sigma,numPts)
>>>plt.plot(x,y,’.’)
>>>plt.show()
Curve Fitting in Python (cont…)
Now let’s define the function to be fit to the
data.
>>>def line(x,m,b):
>>>
return m*x+b
Curve Fitting in Python (cont…)
Using the scipy.optimize.curve_fit module we
perform the fitting.
>>>from scipy.optimize import curve_fit
>>>help(curve_fit)
>>>fit,success=curve_fit(f=line,xdata=x,ydata=y)
>>>print(fit)
Let’s check the results...
>>>x_vals=np.arange(0,np.size(x),0.01)
#Sets up x array.
>>>theory=line(x_vals,fit[0],fit[1])
#Creates theory line from fit
>>>plt.plot(x_vals,theory)
#Plot fit results as line
>>>plt.plot(x,y,’.’)
#Plot data as points
>>>plt.show()
TASK
-Define a function that produces a 1D gaussian curve using the following inputs: mean position,
amplitude, and standard deviation. Verify this by plotting it on a graph. To start set mu=0.0,sigma=1.0,
amp=1.0.
-Create simulated data by adding normally distributed (np.random.normal) random values to a ‘pure’
gaussian. Again, verify by plotting on a graph.
-Using the curve_fit function, fit the gaussian to the simulated data. Do the fit coefficients match the
expected values?
(Helpful commands: np.shape,np.zeros,np.arange)
-->Could we improve the fitting?
-->How could we check the fit results? Or, in other words, how do we estimate how accurate are
the fit parameters to the true value?