Github

A few Python Basics

Style Guide for Python Code: http://www.python.org/dev/peps/pep-0008/


In [3]:
# Create a [list] 
days = ['Monday', # multiple lines 
        'Tuesday', # acceptable 
        'Wednesday',
        'Thursday',
        'Friday',
        'Saturday',
        'Sunday', 
       ] # trailing comma is fine!

In [4]:
days


Out[4]:
['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

In [5]:
# Simple for-loop
for day in days:
    print day


Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday

In [6]:
# Double for-loop
for day in days:
    for letter in day:
        print letter,


M o n d a y T u e s d a y W e d n e s d a y T h u r s d a y F r i d a y S a t u r d a y S u n d a y

In [7]:
# Double for-loop
for day in days:
    for letter in day:
        print letter,
    print


M o n d a y
T u e s d a y
W e d n e s d a y
T h u r s d a y
F r i d a y
S a t u r d a y
S u n d a y

In [8]:
for day in days:
    for letter in day:
        print letter.lower(),


m o n d a y t u e s d a y w e d n e s d a y t h u r s d a y f r i d a y s a t u r d a y s u n d a y

List Comprehensions


In [9]:
length_of_days = [len(day) for day in days]
length_of_days


Out[9]:
[6, 7, 9, 8, 6, 8, 6]

In [ ]:


In [10]:
letters = [letter for day in days
                       for letter in day]

In [12]:
letters = [letter for day in days for letter in day]
print letters


['M', 'o', 'n', 'd', 'a', 'y', 'T', 'u', 'e', 's', 'd', 'a', 'y', 'W', 'e', 'd', 'n', 'e', 's', 'd', 'a', 'y', 'T', 'h', 'u', 'r', 's', 'd', 'a', 'y', 'F', 'r', 'i', 'd', 'a', 'y', 'S', 'a', 't', 'u', 'r', 'd', 'a', 'y', 'S', 'u', 'n', 'd', 'a', 'y']

In [13]:
[num for num in xrange(10) if num % 2]


Out[13]:
[1, 3, 5, 7, 9]

In [14]:
[num for num in xrange(10) if num % 2 else "doesn't work"]


  File "<ipython-input-14-2891a8980b2c>", line 1
    [num for num in xrange(10) if num % 2 else "doesn't work"]
                                             ^
SyntaxError: invalid syntax

In [15]:
[num if num % 2 else "works" for num in xrange(10)]


Out[15]:
['works', 1, 'works', 3, 'works', 5, 'works', 7, 'works', 9]

In [16]:
sorted_letters = sorted([x.lower() for x in letters])
print sorted_letters


['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'e', 'e', 'e', 'f', 'h', 'i', 'm', 'n', 'n', 'n', 'o', 'r', 'r', 'r', 's', 's', 's', 's', 's', 't', 't', 't', 'u', 'u', 'u', 'u', 'w', 'y', 'y', 'y', 'y', 'y', 'y', 'y']

In [17]:
unique_sorted_letters = sorted(set(sorted_letters))

In [18]:
print "There are", len(unique_sorted_letters), "unique letters in the days of the week."
print "They are:", ''.join(unique_sorted_letters)


There are 15 unique letters in the days of the week.
They are: adefhimnorstuwy

In [19]:
print "They are:", '; '.join(unique_sorted_letters)


They are: a; d; e; f; h; i; m; n; o; r; s; t; u; w; y

In [20]:
def first_three(input_string):
    """Takes an input string and returns the first 3 characters."""
    return input_string[:3]

In [21]:
[first_three(day) for day in days]


Out[21]:
['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']

In [22]:
def last_N(input_string, number=2):
    """Takes an input string and returns the last N characters."""
    return input_string[-number:]

In [23]:
[last_N(day, 153) for day in days if len(day) > 6]


Out[23]:
['Tuesday', 'Wednesday', 'Thursday', 'Saturday']

In [24]:
from math import pi

print [str(round(pi, i)) for i in xrange(2, 9)]


['3.14', '3.142', '3.1416', '3.14159', '3.141593', '3.1415927', '3.14159265']

In [27]:
list_of_lists = [[i, round(pi, i)] for i in xrange(2, 9)]
print list_of_lists


[[2, 3.14], [3, 3.142], [4, 3.1416], [5, 3.14159], [6, 3.141593], [7, 3.1415927], [8, 3.14159265]]

In [29]:
for sublist in list_of_lists:
    print sublist


[2, 3.14]
[3, 3.142]
[4, 3.1416]
[5, 3.14159]
[6, 3.141593]
[7, 3.1415927]
[8, 3.14159265]

In [30]:
# Let this be a warning to you!

# If you see python code like the following in your work:

for x in range(len(list_of_lists)):
    print "Decimals:", list_of_lists[x][0], 
    print "expression:", list_of_lists[x][1]


Decimals: 2 expression: 3.14
Decimals: 3 expression: 3.142
Decimals: 4 expression: 3.1416
Decimals: 5 expression: 3.14159
Decimals: 6 expression: 3.141593
Decimals: 7 expression: 3.1415927
Decimals: 8 expression: 3.14159265

In [31]:
# Change it to look more like this: 

for decimal, rounded_pi in list_of_lists:
    print "Decimals:", decimal, "expression:", rounded_pi
    
print list_of_lists


Decimals: 2 expression: 3.14
Decimals: 3 expression: 3.142
Decimals: 4 expression: 3.1416
Decimals: 5 expression: 3.14159
Decimals: 6 expression: 3.141593
Decimals: 7 expression: 3.1415927
Decimals: 8 expression: 3.14159265
[[2, 3.14], [3, 3.142], [4, 3.1416], [5, 3.14159], [6, 3.141593], [7, 3.1415927], [8, 3.14159265]]

In [32]:
# enumerate if you really need the index

for index, day in enumerate(days):
    print index, day


0 Monday
1 Tuesday
2 Wednesday
3 Thursday
4 Friday
5 Saturday
6 Sunday

Dictionaries

Python dictionaries are awesome. They are hash tables and have a lot of neat CS properties. Learn and use them well.


In [33]:
from IPython.display import IFrame, HTML
HTML('<iframe src=https://en.wikipedia.org/wiki/Hash_table width=100% height=550></iframe>')


Out[33]:

In [34]:
fellows = ["Jonathan", "Zach", "Matt", "Wafa"]
sessions = ["2014-C", "2014-C", "2014-A", "2014-B"]

In [35]:
dict(zip(fellows, sessions))


Out[35]:
{'Jonathan': '2014-C', 'Matt': '2014-A', 'Wafa': '2014-B', 'Zach': '2014-C'}

In [36]:
insight = {fellow.lower(): session for fellow, session in zip(fellows, sessions)}

In [37]:
insight


Out[37]:
{'jonathan': '2014-C', 'matt': '2014-A', 'wafa': '2014-B', 'zach': '2014-C'}

In [38]:
# Standard Libraries
# collections; Counter, 
#

In [39]:
insight['matt']


Out[39]:
'2014-A'

In [40]:
rounded_pi = {i:round(pi, i) for i in xrange(2, 9)}

In [41]:
rounded_pi[5]


Out[41]:
3.14159

R or Julia or Haskell or... SQL (get to that later)

You can use R as well -- I don't use it at all, so I took this small example below from http://nbviewer.ipython.org/github/ipython/ipython/blob/3607712653c66d63e0d7f13f073bde8c0f209ba8/docs/examples/notebooks/rmagic_extension.ipynb.


In [ ]:
# This broke!
# There are multiple extensions that allow for R to be executed, this is merely one of them
# I don't use it so I don't know if there's something better. 
# You have to install R as well. 
%load_ext rpy2.ipython

In [ ]:
X = np.array([0,1,2,3,4])
Y = np.array([3,5,4,6,7])

In [ ]:
%%R -i X,Y -o XYcoef
XYlm = lm(Y~X)
XYcoef = coef(XYlm)
print(summary(XYlm))
par(mfrow=c(2,2))
plot(XYlm)

In [ ]:
FileLink("Overview.ipynb")