Download Python Workshop 1 - University of Florida Astronomy

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
GAO Workshop
Series
UF Astronomy
Python Workshop 1
Why Python?
● Actively being developed, while also being wellestablished
● Powerful and free
● Becoming a base/glue for many other utilities (e.g., Pyraf,
CASA)
● Replacing IDL as the standard programing language in
astronomy.
● Augmented with professional and highly flexible plotting
utilities
● Desired skill in and out of academia
Getting Started
● Go to your command line
● Type 'python'
○ This will start the Python shell, which is what we will
use today.
● In the shell type
○ >>print 'Hello World!'
Which Python Shell to Use?
● Python Shell
○ Basic, universal
● Ipython
○ More features, %magic commands, logs, etc.
● Ipython Notebook
○ Mathematica like notebook
○ Code runs in 'cells'
○ Inline plots and LaTex rendered notes
● Don't forget about old skool
○ vim with a shebang
Example of an Ipython Notebook
Variables
>>> alice
>>> bob =
>>> print
1
>>> print
pony
= 1
'pony'
alice
bob
● Can do more than one at a time, too!
>>> bob, alice, chris = 2, 'cows', 'in the barn'
>>> print bob, alice, chris
2 cows in the barn
Reserved Words
You may not name your variables any of the
following words as they mean special things in
Python:
and
as
assert
break
class
continue
def
del
elif
else
except
exec
finally
for
from
global
if
import
in
is
lambda
not
or
pass
print
raise
return
try
while
with
yield
Data Types
Python supports the
following data types:
boolean
integer
long
float
string
list
object
None
Example:
bool = True
name = "Craig"
age = 26
pi = 3.14159
print(name + ' is ' + str(age)
+ ' years old.')
-> Craig is 26 years old.
Import
HTTP://IMGS.XKCD.
COM/COMICS/PYTHON.PNG
import math
>>>math.sqrt(2)
import math as M
>>>M.sqrt(2)
from math import sqrt
>>>sqrt(2)
from math import *
>>>use any function now
It's a list!
>>> I_am_a_list=['Yes',123,5.0,"'Twas Brillig"]
>>> for item in I_am_a_list: print item
...
Yes
123
5.0
'Twas Brillig
>>> print I_am_a_list[1]
123
lists
●
●
●
●
●
●
Denoted with [ ]
Items separated with commas
Ordered
Indexed with an integer from 0
Values can be changed
Can change list size using methods such as
list.pop(i) for removing the ith element
● See lists in the python docs
It's a more complicated list
>>>I_am_a_list=[('Yes','No'),(123,789),(5.0,10.0),("'Twas
brillig, and the slithy toves" , "Did gyre and gimble in
the wabe;" , "All mimsy were the borogoves," , "And the
mome raths outgrabe.")]
>>> for item in I_am_a_list:
...
for element in item: print element
...
print "--"
...
Yes
No
...SNIP FOR SPACE...
-5.0
10.0
-'Twas brillig, and the slithy toves
Did gyre and gimble in the wabe;
All mimsy were the borogoves,
And the mome raths outgrabe.
--
Tuples - The Indestructible List
>>> bob = (1,3.42,'a pony')
>>> for x in bob : print x
...
1
3.42
a pony
Just like a list, but can't be changed after
creation.
Dictionaries
>>> info = {'name' : 'Robert', 'height' : 1.9, 'weight' : 'Too much'}
>>> print info[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 0
>>> print info['name']
Robert
>>> print info['weight']
Too much
>>> print info['height']
1.9
Dictionaries
● Denoted with { }
● Made up of key : value pairs separated with
commas
● Unordered
● Keys are strings
● Values can be any type, including lists, other
dictionaries, even functions!
● Use dict.keys() to get a list of keys
● Use dict.values() to get a list values
Dictionaries are really, really useful!
Loops
for i in xrange(n): do something
for i in xrange(2,n-2): do some more
● Be careful! A loop using xrange(a,b) should be read as
●
●
over the range [a,b).
The len command is also quite useful. ...xrange(len
(array)):
Combine element looping and iteration:
○ for iter,item in enumerate(array):
■ iter is now an integer and item is the value in the
array of the ith element.
Indentation
In Python, loops are denoted by indentation. Loops are
closed when the indentation returns to the previous level.
Example:
>>> for k in range(0,2) :
...
print k
...
0
1
Indentation
Standard practice is 4 spaces (not tabs*) for
each level:
>>> for k in range(0,2) :
...
for j in range(0,2) :
...
print k,j
0 0
0 1
1 0
1 1
*In the shell and editors with a Python mode, pressing tab
is really inserting 4 spaces.
Loop: see Loop
while True:
if condition true: break
while condition is true:
loop and loop away
while not condition is false:
loop and loop some more
if conditional and conditional:
do something
elif not conditional:
do something
elif conditional or conditional:
do something
else conditional:
do something
Comparisons
Operation
<
<=
>
>=
==
!=
is
is not
Meaning
strictly less than
less than or equal
strictly greater than
greater than or equal
equal
not equal
object identity
negated object identity
Boolean Operations — and, or, not
Operation Result
x or y
if x is false, then y, else x
x and y
if x is false, then x, else y
not x
if x is false, then True, else
False
>>> bob, alice, chris = 'pony', 'cows', 2
>>> if bob != alice and chris == 2 : print
'I like cake!'
...
I like cake!
Loop through a file
handle=open('path/to/filename','r')
for line in handle:
do something with line
handle.seek(0)
for line in handle:
for some reason go through the file again
# close up shop
handle.close()
Reverse and return a character
def reverse_string(char_array):
rev_char_array=""
n=len(char_array)
for i in xrange(n):
rev_char_array+=char_array[n-i1]
return rev_char_array
>>> reverse_string("Live")
'eviL'
>>> string="Live"
>>> print string[::-1]
eviL
Create the pow function
def pow(a,b):
'''Return the value of a^b for integer
b'''
if b==0:return 1
t=1
return pown(a,t,b)
def pown(a,t,b):
if t<b:
t+=1
a*=pown(a,t,b)
return a
Fibonacci
def add_seq(a,b,i,n):
if i==1:a=0;b=0
elif i<=3:a=0;b=1
c=a+b
a=b;b=c
if i<n:
print i,b; i+=1
b=add_seq(a,b,i,n)
elif n>0: print i,b
def fib(n):
'''fib(n) lists up to the nth sequence in the Fibonacci
sequence.'''
a=0.;b=0.;i=1; print "Number Value";add_seq(a,b,i,
n)
Functions of Functions
>>> def a(x):
...
return "a({})".format(x,)
...
>>> def b(f,x):
...
return f(x)
...
>>> print b(a,10)
a(10)
>>>
Example from StackOverflow
Let's get real
A few examples:
ugly data file
http://www.astro.ufl.edu/~aaron.boley/media/data/log.exple
script to read
http://www.astro.ufl.edu/~aaron.boley/media/data/read_log.py
More complex example: go to the aviation tab on Aaron's
Web site and get the A/FD script
Rescources
● Craig's Cheat Sheet
●
○ http://www.astro.ufl.edu/~warner/prog/python.html
Python v2.7.3 documentation
○ http://docs.python.org/index.html