In [1]:
from __future__ import absolute_import, division, print_function

Github

A few Python Basics


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

In [ ]:
days

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

In [ ]:
# Double for-loop
for day in days:
    for letter in day:
        print(letter)

In [ ]:
print(days)

In [ ]:
print(*days)

In [ ]:
# Double for-loop
for day in days:
    for letter in day:
        print(letter)
    print()

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

List Comprehensions


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

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

In [ ]:
print(letters)

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

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

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

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

In [ ]:
[num for num in xrange(10)]

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

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

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

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

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

In [ ]:
import numpy as np

In [ ]:
# tab
np.linspace()

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

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

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

In [ ]:
from math import pi

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

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

In [ ]:
for sublist in list_of_lists:
    print(sublist)

In [ ]:
# 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], "expression:", list_of_lists[x][1])

In [ ]:
print(list_of_lists)

# Change it to look more like this: 

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

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

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

Dictionaries

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


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

In [ ]:
fellows = ["Jonathan", "Alice", "Bob"]
universities = ["UCSD", "UCSD", "Vanderbilt"]

In [ ]:
for x, y in zip(fellows, universities):
    print(x, y)

In [ ]:
# Don't do this
{x: y for x, y in zip(fellows, universities)}

In [ ]:
# Doesn't work like you might expect
{zip(fellows, universities)}

In [ ]:
dict(zip(fellows, universities))

In [ ]:
fellows

In [ ]:
fellow_dict = {fellow.lower(): university 
                   for fellow, university in zip(fellows, universities)}

In [ ]:
fellow_dict

In [ ]:
fellow_dict['bob']

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

In [ ]:
rounded_pi[5]

In [ ]:
sum([i ** 2 for i in range(10)])

In [ ]:
sum(i ** 2 for i in range(10))

In [ ]:
huh = (i ** 2 for i in range(10))

In [ ]:
huh.next()