Nathan Lloyd
<shift><enter>
to execute the cellmy_name = 'ari'
my_name
2 + 2
example_variable = 2 + 2
example_variable
example_variable = example_variable + 5
example_variable
<tab>
, it will complete with "example_variable")%%time
at the beginning of a cell will print out how long it took to run the code<shift><enter>
to run the code in the cell<shift><enter>
to run the code in the cell<command>z
to undo edits<tab>
to indent it<ctrl><shift>-
<escape>
while in edit mode to switch to command mode.You can also change cell type using the "Cell" pull-down menu.
By the way, "Markdown" is what I'm using to make these nice text cells (you can even have tables!) - see Markdown Cheatsheet.
"Raw" is a good way to comment out a cell so it won't run.
# Execute me by hitting <shift><enter>
for i in range(7):
print(i)
<shift><tab>
to see documentation.range(7)
spits out 0 to 6 because python indexing is 0-based. More on that later.for i in range(2):
print(i)
print("yo")
print("dude")
Hint: use <shift><tab>
trick to see documentation for print function
for i in range(7):
print(i)
s = ""
for i in range(7):
s=s+str(i)
print(s)
for i in range(7):
print(i,end='')
Execute cell below to get solution
%load exercise_print_without_newline.py
example_list = ['alpha', 'bravo', 2, print]
type(example_list)
# Print each item in the list
for item in example_list:
print(item,end="")
# Access the second item in the list (0-based indexing!)
example_list[1]
example_tuple = ('alpha', 'bravo', 2, print)
type(example_tuple)
for item in example_tuple:
print(item)
example_tuple[0]
Tuple is just like list except it's static.
Use lists unless you know you need a tuple.
example_dict = {'a':63, 7:'a', 'g':print} # {key:value, key:value, key:value}
type(example_dict)
example_dict
example_dict['a']
example_dict[7]
# Raises Exception KeyError if you query a key that is not in the dict
# You can do example_dict.get(key, default_value) to gracefully return, e.g. 0 when the key is missing.
example_dict[15]
example_dict['g']
Common mistake: example_dict[g]
would throw an exception. You need those quotes.
# example_dict['g'] is a function, so we can use it like a function
example_dict['g']("you coding, bro?")
' A String '
type(' A String ')
# The str type has lots of useful functions
' A String '.strip().lower()
See what each of those functions, .strip()
and .lower()
do separately.
' A String k '.strip()
'A String'.lower()
dict
dictionary = {'g':print}
k = str(dictionary['g']('whAt up'))
print(k.lower())
'Jack' == 'jack' # comparison of strings
'Jack'.lower() == 'jack'.lower() # comparison of strings
'time' + 'honey' # can "add" strings.
a = 'FANTASTIC!'
a.lower()
a = 3
a.lower() # throws Exception
AttributeError
is an exception that python throws when it gets this bad input.
Earlier we saw a dict
throw the exception KeyError
when I queried a key that wasn't present.
Often times an exception get thrown, like, 4 layers deep in function calls, e.g. e(f(g(h(whathaveyou)))
and the function h
has a problem operating on whathaveyou
. In that case you get a traceback that shows the layers, which is long, but you get used to it.
Often the error message is not helpful. Keep calm and google it.
# Remember that crazy list of mixed types from earlier?
example_list = ['alpha', 'bravo', 2, print]
for item in example_list:
item('works!')
Here, TypeError
is thrown on the first iteration of the for loop because the first item, 'alpha'
, is not a function, and you can only do something(input)
if something
is a function (well, there's other things it could be, e.g. a class, but you get the point).
# try: except: clause to handle exceptions
for item in example_list:
try:
item('carl is my therapist')
except:
print("Error: {} doesn't work".format(item))
# Can also get more information on what's causing the exception
for item in example_list:
try:
item('carl is my therapist')
except:
print("Error: {} doesn't work".format(item))
print(type(item))
color = 'blue'
type
, len
, and str.upper
for func in your_list:
print(func(color))
color = 'blue'
listed = [type, len, str.upper]
for items in listed:
print(items(color))
Execute cell below to get solution
%load exercise_list_functions.py
'nothing'
to the list, so that we get an exception thrown when python tries to execute it.try: except:
clause to gracefully handle the exception.listed.append('nothing')
print(listed)
for func in listed:
try:
print(func(color))
except:
print('oh shit'.upper(),sep='',end='.')
Execute cell below to get solution
%load exercise_list_functions_try_except.py
Example dataset: housing values for in Boston:
http://archive.ics.uci.edu/ml/datasets/Housing
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('ggplot')
%matplotlib inline
df = pd.read_csv('housing.txt', sep='\t')
df
fig, ax = plt.subplots(1, 1)
ax.scatter(x=df['crime'], y=df['median_value'])
ax.set_xlabel('crime per capita')
ax.set_ylabel('median value / $1000');
fig, ax = plt.subplots(1, 1)
ax.scatter(x=df['nox'], y=df['median_value'])
ax.set_xlabel('Nitric oxides concentration (parts per 10M)')
ax.set_ylabel('median value / $1000')
import numpy as np
fig, ax = plt.subplots(1, 1)
ax.scatter(x=df['nox'], y=df['median_value'], s=3*df['rooms']**2, c=np.sqrt(df['crime']), alpha=0.25, cmap='viridis')
ax.set_xlabel('Nitric oxides concentration (parts per 10M)')
ax.set_ylabel('median value / $1000')
df['median_value'].hist()