Talk given to full stack program cohort at Galvanize/Boulder on September 14, 2016 about a few reasons why Python is awesome.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

218 KiB

7 Reasons Why I <3 Python

Keith Maull / Sep. 14, 2016 / Galvanize gSchool Boulder

1. It is beautiful, clean and precise

In [1]:
def gcd(a,b):
    while b != 0:
        a, b = b, a%b
    return a

tests = [(216,846), (1071,462), (1024,768)]

for a, b in tests:
    print("The gcd of {} and {} is {}.".format(a, b, gcd(a,b)))
The gcd of 216 and 846 is 18.
The gcd of 1071 and 462 is 21.
The gcd of 1024 and 768 is 256.
In [2]:
if 1 and True:
    print("1 and True is True")
if not(0 or False):
    print("0 or False is False")
1 and True is True
0 or False is False
In [3]:
def outer(v1, v2):
    # defining a nested function
    def inner(iv1, iv2):
        print("Outer v1={}, Outer v2={}".format(v1, v2))
        print("Outer iv1={}, Outer iv2={}".format(iv1, iv2))
    
    inner(3,4)
    
outer(1,2)
Outer v1=1, Outer v2=2
Outer iv1=3, Outer iv2=4

2. Text and Strings are a joy to work with!

In [4]:
lorem_text = """
Lorem ipsum dolor sit amet, consectetur adipiscing elit. In sed iaculis sapien, vitae vestibulum nunc. Vivamus pharetra risus neque, ut iaculis elit porta non. Vivamus ullamcorper dolor sit amet sollicitudin vehicula. Aliquam quis tristique nibh, eget malesuada purus. Proin varius sollicitudin turpis, fermentum mollis elit cursus vel. Suspendisse vehicula enim ac magna consequat ultricies. Pellentesque in leo et nulla porta faucibus. Quisque tincidunt in erat ut commodo. Quisque id augue a nisl mollis pulvinar id at nulla. Morbi a augue erat. Sed pharetra molestie mauris nec ultricies. Pellentesque efficitur blandit mauris, sed vulputate ante bibendum eu. Nulla facilisi. Sed porta massa eu ligula tristique, nec hendrerit elit euismod. Phasellus luctus placerat facilisis.
"""

for t in lorem_text.split():
    print t
Lorem
ipsum
dolor
sit
amet,
consectetur
adipiscing
elit.
In
sed
iaculis
sapien,
vitae
vestibulum
nunc.
Vivamus
pharetra
risus
neque,
ut
iaculis
elit
porta
non.
Vivamus
ullamcorper
dolor
sit
amet
sollicitudin
vehicula.
Aliquam
quis
tristique
nibh,
eget
malesuada
purus.
Proin
varius
sollicitudin
turpis,
fermentum
mollis
elit
cursus
vel.
Suspendisse
vehicula
enim
ac
magna
consequat
ultricies.
Pellentesque
in
leo
et
nulla
porta
faucibus.
Quisque
tincidunt
in
erat
ut
commodo.
Quisque
id
augue
a
nisl
mollis
pulvinar
id
at
nulla.
Morbi
a
augue
erat.
Sed
pharetra
molestie
mauris
nec
ultricies.
Pellentesque
efficitur
blandit
mauris,
sed
vulputate
ante
bibendum
eu.
Nulla
facilisi.
Sed
porta
massa
eu
ligula
tristique,
nec
hendrerit
elit
euismod.
Phasellus
luctus
placerat
facilisis.
In [5]:
for w in lorem_text.split():
    if w[-1] in [',', "."]:
        print w[:-1]
    else:
        print w
Lorem
ipsum
dolor
sit
amet
consectetur
adipiscing
elit
In
sed
iaculis
sapien
vitae
vestibulum
nunc
Vivamus
pharetra
risus
neque
ut
iaculis
elit
porta
non
Vivamus
ullamcorper
dolor
sit
amet
sollicitudin
vehicula
Aliquam
quis
tristique
nibh
eget
malesuada
purus
Proin
varius
sollicitudin
turpis
fermentum
mollis
elit
cursus
vel
Suspendisse
vehicula
enim
ac
magna
consequat
ultricies
Pellentesque
in
leo
et
nulla
porta
faucibus
Quisque
tincidunt
in
erat
ut
commodo
Quisque
id
augue
a
nisl
mollis
pulvinar
id
at
nulla
Morbi
a
augue
erat
Sed
pharetra
molestie
mauris
nec
ultricies
Pellentesque
efficitur
blandit
mauris
sed
vulputate
ante
bibendum
eu
Nulla
facilisi
Sed
porta
massa
eu
ligula
tristique
nec
hendrerit
elit
euismod
Phasellus
luctus
placerat
facilisis
In [6]:
for w in lorem_text.split()[:5]:
    if w[-1] in [',', "."]:
        print w[:-1].lower()
    else:
        print w.lower()
lorem
ipsum
dolor
sit
amet
In [7]:
for w in reversed(lorem_text.split()[:5]):
    print w
amet,
sit
dolor
ipsum
Lorem
In [8]:
e_word_count = 0
for w in lorem_text.split():
    if 'e' in w:
        e_word_count += 1

print e_word_count
55
In [9]:
def lorem_clean_sample(start, end):
    sample = []
    
    for w in lorem_text.split()[start:end]:
        if w[-1] in [',', "."]:
            sample.append(w[:-1].lower())
        else:
            sample.append(w.lower())
    
    return sample

3. There are just enough data types to get started ...

In [10]:
# dictionaries / maps
d = {"a": 1}

# tuples (immutable "lists")
tup = ("b", 2) 

# lists [1, 2, 3]
lis = ["c", 1]

... and they play well together

In [11]:
list(tup)
Out[11]:
['b', 2]
In [12]:
tuple(lis)
Out[12]:
('c', 1)
In [13]:
dict([tuple(lis)])
Out[13]:
{'c': 1}
In [14]:
dict([tup])
Out[14]:
{'b': 2}
In [15]:
dict.fromkeys(["a", "b", "c"])
Out[15]:
{'a': None, 'b': None, 'c': None}
In [16]:
dict.fromkeys(("a", "b", "c"))
Out[16]:
{'a': None, 'b': None, 'c': None}
In [17]:
d = dict.fromkeys(["a", "b", "c"])
d
Out[17]:
{'a': None, 'b': None, 'c': None}
In [18]:
d.update(dict([tuple(lis)]))
In [19]:
d
Out[19]:
{'a': None, 'b': None, 'c': 1}
In [20]:
d.update(dict([('a',1), tuple(lis), tup]))
In [21]:
d
Out[21]:
{'a': 1, 'b': 2, 'c': 1}

4. And there are some nice short cuts ...

In [22]:
# list comprehensions
[i for i in xrange(1,16)]
Out[22]:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
In [23]:
[i for i in xrange(1,16) if i%2]  # say what???
Out[23]:
[1, 3, 5, 7, 9, 11, 13, 15]
In [24]:
[i for i in xrange(1,16) if not i%2]  # aha!!!
Out[24]:
[2, 4, 6, 8, 10, 12, 14]
In [25]:
# dictionary comprehensions
lorem_wlen = {key: len(key) for key in lorem_clean_sample(0, 10)}
lorem_wlen
Out[25]:
{'adipiscing': 10,
 'amet': 4,
 'consectetur': 11,
 'dolor': 5,
 'elit': 4,
 'in': 2,
 'ipsum': 5,
 'lorem': 5,
 'sed': 3,
 'sit': 3}
In [26]:
lorem_cnt_e = {key: key.count("e") for key in lorem_clean_sample(0, 10)}
lorem_cnt_e
Out[26]:
{'adipiscing': 0,
 'amet': 1,
 'consectetur': 2,
 'dolor': 0,
 'elit': 1,
 'in': 0,
 'ipsum': 0,
 'lorem': 1,
 'sed': 1,
 'sit': 0}

5. Batteries included ....

In [27]:
import requests

r = requests.get("http://www2.ed.gov/data.json")
if r.status_code == 200:
    payload_dict = r.json()  # loading the data into a dict via the json() just works!
else: 
    print "Could not load the data at this endpoint."
In [28]:
payload_dict.keys()
Out[28]:
[u'conformsTo', u'dataset', u'describedBy', u'@context', u'@id', u'@type']
In [29]:
arra_data = {}
for dataset in payload_dict['dataset']:
    
    if "ARRA" in dataset['description']:
        
        dsid = dataset['identifier']
        desc = dataset['description']
        title = dataset['title']
        
        arra_data[dsid] = {'description': desc, 'title': title}
In [30]:
arra_data
Out[30]:
{u'ED-2485': {'description': u'The Investing in Innovation (i3) Fund website depicts and allows downloading of general information on the i3 applicants received, grantees awarded and project locations. The Investing in Innovation Fund, established under section 14007 of the American Recovery and Reinvestment Act of 2009 (ARRA), provides funding to support (1) local educational agencies (LEAs), and (2) nonprofit organizations in partnership with (a) one or more LEAs or (b) a consortium of schools. The purpose of the i3 program is to provide competitive grants to applicants with a record of improving student achievement and attainment in order to expand the implementation of, and investment in, innovative practices that are demonstrated to have an impact on improving student achievement or student growth, closing achievement gaps, decreasing dropout rates, increasing high school graduation rates, or increasing college enrollment and completion rates. These grants will (1) allow eligible entities to expand and develop innovative practices that can serve as models of best practices, (2) allow eligible entities to work in partnership with the private sector and the philanthropic community, and (3) identify and document best practices that can be shared and taken to scale based on demonstrated success.',
  'title': u'ED Grants: Investing in Innovation (i3) Fund 2010'},
 u'ED-5562': {'description': u'The Investing in Innovation (i3) Fund website depicts and allows downloading of general information on the i3 applicants received, grantees awarded and project locations. The Investing in Innovation Fund, established under section 14007 of the American Recovery and Reinvestment Act of 2009 (ARRA), provides funding to support (1) local educational agencies (LEAs), and (2) nonprofit organizations in partnership with (a) one or more LEAs or (b) a consortium of schools. The purpose of the i3 program is to provide competitive grants to applicants with a record of improving student achievement and attainment in order to expand the implementation of, and investment in, innovative practices that are demonstrated to have an impact on improving student achievement or student growth, closing achievement gaps, decreasing dropout rates, increasing high school graduation rates, or increasing college enrollment and completion rates. These grants will (1) allow eligible entities to expand and develop innovative practices that can serve as models of best practices, (2) allow eligible entities to work in partnership with the private sector and the philanthropic community, and (3) identify and document best practices that can be shared and taken to scale based on demonstrated success.',
  'title': u'ED Grants: Investing in Innovation (i3) Fund 2011'}}
In [31]:
arra_data_dc = { dataset['identifier'] : 
                {'description': dataset['description'], 
                 'title': dataset['title']}
                for dataset in payload_dict['dataset'] 
                if "ARRA" in dataset['description'] }    
In [32]:
arra_data_dc
Out[32]:
{u'ED-2485': {'description': u'The Investing in Innovation (i3) Fund website depicts and allows downloading of general information on the i3 applicants received, grantees awarded and project locations. The Investing in Innovation Fund, established under section 14007 of the American Recovery and Reinvestment Act of 2009 (ARRA), provides funding to support (1) local educational agencies (LEAs), and (2) nonprofit organizations in partnership with (a) one or more LEAs or (b) a consortium of schools. The purpose of the i3 program is to provide competitive grants to applicants with a record of improving student achievement and attainment in order to expand the implementation of, and investment in, innovative practices that are demonstrated to have an impact on improving student achievement or student growth, closing achievement gaps, decreasing dropout rates, increasing high school graduation rates, or increasing college enrollment and completion rates. These grants will (1) allow eligible entities to expand and develop innovative practices that can serve as models of best practices, (2) allow eligible entities to work in partnership with the private sector and the philanthropic community, and (3) identify and document best practices that can be shared and taken to scale based on demonstrated success.',
  'title': u'ED Grants: Investing in Innovation (i3) Fund 2010'},
 u'ED-5562': {'description': u'The Investing in Innovation (i3) Fund website depicts and allows downloading of general information on the i3 applicants received, grantees awarded and project locations. The Investing in Innovation Fund, established under section 14007 of the American Recovery and Reinvestment Act of 2009 (ARRA), provides funding to support (1) local educational agencies (LEAs), and (2) nonprofit organizations in partnership with (a) one or more LEAs or (b) a consortium of schools. The purpose of the i3 program is to provide competitive grants to applicants with a record of improving student achievement and attainment in order to expand the implementation of, and investment in, innovative practices that are demonstrated to have an impact on improving student achievement or student growth, closing achievement gaps, decreasing dropout rates, increasing high school graduation rates, or increasing college enrollment and completion rates. These grants will (1) allow eligible entities to expand and develop innovative practices that can serve as models of best practices, (2) allow eligible entities to work in partnership with the private sector and the philanthropic community, and (3) identify and document best practices that can be shared and taken to scale based on demonstrated success.',
  'title': u'ED Grants: Investing in Innovation (i3) Fund 2011'}}

6. Juptyer Notebooks

In [33]:
import csv

with open("Export.csv") as fi:
    csv_fi = csv.DictReader(fi)
    for row in csv_fi:
        print row['MarketName'], row['x'], row['y']
        break
 Caledonia Farmers Market Association - Danville -72.140305 44.411013
In [34]:
map_data_objects = {}
with open("Export.csv") as fi:
    csv_fi = csv.DictReader(fi)
    for row in csv_fi:
        try:
            map_data_objects[row['FMID']] = (row['MarketName'], float(row['x'].strip()), float(row['y'].strip()))
        except ValueError:
            print("Count not convert row for FMID: {}".format(row['FMID']))
Count not convert row for FMID: 2000001
Count not convert row for FMID: 1011689
Count not convert row for FMID: 2000002
Count not convert row for FMID: 1002854
Count not convert row for FMID: 2000004
Count not convert row for FMID: 2000005
Count not convert row for FMID: 2000006
Count not convert row for FMID: 2000007
Count not convert row for FMID: 2000008
Count not convert row for FMID: 2000009
Count not convert row for FMID: 2000010
Count not convert row for FMID: 2000011
Count not convert row for FMID: 2000012
Count not convert row for FMID: 2000013
Count not convert row for FMID: 2000014
Count not convert row for FMID: 2000016
Count not convert row for FMID: 2000017
Count not convert row for FMID: 2000019
Count not convert row for FMID: 2000020
Count not convert row for FMID: 2000021
Count not convert row for FMID: 2000022
Count not convert row for FMID: 2000026
Count not convert row for FMID: 2000028
Count not convert row for FMID: 2000030
Count not convert row for FMID: 2000032
Count not convert row for FMID: 2000033
Count not convert row for FMID: 2000034
Count not convert row for FMID: 2000035
Count not convert row for FMID: 2000036
In [35]:
import folium

us_fm_map = folium.Map(location=[39.232253, -97.910156],
                   zoom_start=4,
                   tiles='Stamen Terrain')

for fmid, v in map_data_objects.iteritems():
    name, lon, lat = v
    
    if (lon < -104 and lon > -106) \
        and \
        (lat < 43 and lat > 30):
            folium.Marker([lat, lon],
                       popup=unicode(name.decode('utf-8'))
                      ).add_to(us_fm_map) 
In [36]:
us_fm_map
Out[36]:

7. The community ...

Now go play ...