Resources
- Python data types cheat sheet
- Python loops cheat sheet
- state_capitals.py -- the state capitals example.
- cdsw-au2015-lecture1-20151010.ogv -- Professor Mako Hill's lecture video, which covers most of the concepts from today's lecture.
Lecture outline
Lists
- purpose
- Stores things in order
- initialization
- making a list called my list:
my_list = ["a", "b", "c"]
- comma separated elements. in python they can be a mix of any kind of types
type(my_list)
- making a list called my list:
- len() review
- accessing elements
- indexing like my_list[0]
- indexing starts from the front and we start counting at 0 (now you understand all the zeros we've been using)
- we go from the end with negative numbers
- what happens if we try to move outside of the range? ('error!)
- adding elements
- using the the
my_list.append()
function - the
.append()
function is a special kind of function that lists know about
- using the the
- changing elements
- replacing elements like
my_list[0] = "foo"
- replacing elements like
- finding elements in list
- e.g.,
"z" in my_list
- e.g.,
- slicing lists
- the colon inside the [] is the slicing syntax
- e.g.,
my_list[0:2]
is 0th up to, but not including, the 2nd - e.g.,
my_list[2:]
- e.g.,
my_list[:2]
- e.g.,
my_list[:]
- strings are like lists
- we can slice lists
- len()
len("")
length of the empty string
- many other interesting functions for lists
- e.g.,
min()
andmax()
- e.g., create a list of names and sort it
names.sort()
- e.g.,
loops and more flow control
- for loops
- e.g.,
for name in names: print name
- e.g.,
for name in names: print 'hello ' + name
- Super powerful because it can do something many many times. Data science is about doing tedious things very quickly. For is the workhorse that makes this possible.
- Look and see name is after we're done looping.
- Move to editor.
- e.g.,
- if statements inside for loops
- e.g.,
if name[0] in "AEIOU"
then print "starts with a vowel" - show we can test things outside the loop to show how the comparisons are working
- add an else statement to capture words that start with a consonant
- append to a list within a for loop
- create a counter within a for loop (keep track)
- build up a sentence
- e.g.,
- nested for loops
- range()
- while loops
- infinite loops
- if statements inside while loops
- break
- input()
dictionaries
- purpose
- initialization
- accessing elements
- adding elements
- changing elements
- keys() and values()
modules
- purpose
- builtins
- imports
- import random
- random.randint
- random.choice
walk through state_capitals.py
Where state_capitals.py from http://mako.cc/teaching/2015/cdsw-spring/state_capitals.py is the grand finale and synthesis of lecture material.