Choose Your Own Pyventure/Midclass Review

REVIEW

edit

Okay, it's not all review. Some of it is new. The rest of it is review.

These examples and questions should be challenging! Get in, and get dirty! The only way to learn to code is to try to make code. When it breaks:

  • take a deep breath
  • read the error message. They are often quite informative.
  • check your
    • indentation
    • matching parentheses / braces / brackets / quotes
    • ego. We all make mistakes!


If you're confused about anything here, seek out a more complete Python reference, or bring questions to class.


Dictionaries

edit
  • dicts associate keys with values
  • are accessed through their keys
  • have no inherent order
  • Exercise: Create the dictionary D, which we'll use throughout the exercises. Note: we can use the dict() function to make a dictionary as well.
D = {'i':1, 'l': [1,2,3], 's': "my favorite string", d= dict(a=1,b=2)}

What is broken here? Now try this.

D = {'i':1, 'l': [1,2,3], 's': "my favorite string", 'd': dict(a=1,b=2)}
  • what are the keys of D
Answer

get all keys:

   d.keys()  # this won't work since d isn't defined!
   D.keys()
  • what are the values?
Answer

get values:

   D.values()


  • try to access the values of D
Answer

Accessing:

   D['i']
   D['d']
   D['c']  # what happens when it doesn't exist?
  • try deleting a key-value pair from D
Answer

delete using del

   del D['i']
   del D['c']
  • try adding a key-value pair to D: 'newkey' -> True
Answer

adding:

   D['newkey'] = True
  • Examine the get method of dictionaries
    1. help(D.get)
    2. try:
      • D.get('i',"notfound")
      • D.get('c',"notfound")
Answer

Help on built-in function get:

   get(...)
       D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None.
       

Bascially, return D[k] if k is in D, otherwise, return d. This saves our bacon from having a KeyError when a key isn't in the dictionary.

  • extra credit: try dict(1='a'). Predict what will happen, and explain it.
    1. dict(a=1)
    2. dict('a'=1)
    3. dict(class=1)
    4. help(dict)
Answer

1 isn't a valid python variable name. The dict() function expects valid python identifiers, as described in the help.


  • extra credit: What is the first element of D?


Answer

Trick question! Dictionaries don't have inherent order! It may vary from machine to machine or from python version to python version. In any case, it's not something to rely on.

Lists, Tuples, Strings

edit

List, tuples and strings are all python sequence types

  • they are ordered
  • they are accessed by their index [0,..,n], unlike dictionaries, which are accessed by key
  • some are mutable (meaning the elements can change)
  • strings have additional methods like upper, lower, split etc.
  • sequences support slicing (see below)
  • construct L,t,s like this:
   L = [8,'a',[1,2,3],None,'b']
   t = ('hallway', "a creepy hallway!")
   s = "a few of my favoirite strings"


  • try accessing different elements.
   L[0]
   s[1]
   t[2]
   L['a'] 
Answer

L['a'] fails because sequences are accessed by index not by name.

  • which ones are immutable?
   L[0] = 1
   s[0] = 1
   t[0] = 1
   
Answer

Tuples and Strings are immutable. Tuples imply that the positions mean something, where lists can be appended to, deleted from, and the like.


  • extra credit experiements in slicing
   L[:2]
   L[2:]
   L[-3]
   L[10]
   L[::-1]


Functions

edit
  • make this function:
   yell_month(name,monthint) -> string

that works like this:

   >>> yell_month('gregg', 1)
   'January GREGG'
   >>> yell_month('mIRANda', 7)
   'July MIRANDA'
  • try it using a dictionary, and if/elif/else statements
Answer

two methods

   # here's one method, using a dict. 
   def yell_month(name,monthint):
       months = {1: 'January', 2: 'February', }  # etc.
       name = name.strip().upper()
       return months.get(monthint, "MONTHUARY") + " " + name
   # another, using if/else
   def yell_month(name,monthint):
       month = "SMARCH"
       if monthint == 1:
           month = "January"
       elif monthint == 2:
           month = "February"
       ... # lots of omitted code
       else:
           month = "SMARCH"
       name = name.strip().upper()
       return month + " " + name
   
   # which do you think is easier?


Loops

edit

Sometimes we want to do things more than once. Computers don't get bored by repetitive work, and have infinite patience. Exploit this!


Iterators

edit

Python has a magic appearing construct called for...in, that iterates over data structures.

   for element in thing:
       print element, type(element)

Try iterating over our sequences, substituting our friends D,s,t,L for 'thing'.

Answer

iterator example

   for thing in (D,s,t,L): 
       print thing
       for element in thing:
           print element, type(element)


While Loops

edit

The while constructor runs the body of the loop for as long as the condition is True.

Here is an example:

def countdown(n):
    while n >= 1:
        print n
        n = n -1
    print "liftoff"


  • try this with different values for n, like 0, 1, -1, 'a', None
  • write a function that counts up to a number.
  • final_countdown, which despite its name, uses a for loop
def final_countdown():
    ''' print a version  of Europe's 'The Final Countdown' '''
    phrases = [ 
            'do de do dooo',
            'do de do do dooo',
            'de do de do',
            'de do de do do de dooo'
            'do de doo', 
            'do de do',
            'do de do do deee dooooo',
            'WEEEEE WOOOOOOOO',
    ]
    for phrase in phrases:
        print phrase

extra credit: make countdown wait

edit

What if we actually want the function to wait one second between loops? There is a python function called [time.sleep] that we can use.

Example showing time.sleep
import time
def countdown(n, wait=1):
    while n >= 1:
        print n
        time.sleep(wait)
        n = n -1
    print "liftoff"

countdown(5,.5)

extra credit: break and continue

edit
  • break breaks out of a loop
  • continue goes on to the repeat in the loop
examples

example with continue and break:

   def cases_spaces_breaks(sentence):
       for letter in sentence:
           if letter == " ":
               break
           elif letter.islower():
               continue
           elif letter.isupper():
               print  letter, "is uppity!"
           else:
               print letter, "is middle cased?"
  • try this out with various input sentences, to discover what it does


The Standard Library

edit

Explore the standard library.

  • Choose a function or module, and experiment with it.
  • Tell the class which one you chose!
  • Show some code using it.
  • Describe its inputs and outputs.


Get Dirty!

edit

Look at the standard exceptions (errors), and see which ones you recognize. Try to write code that triggers these errors:

  • SyntaxError
  • KeyError
  • NameError
  • TypeError (hint: int() is a good candidate!)
  • IndexError
  • ImportError
Answer

Generate some errors:

   a = '1 # SyntaxError
   {}['a'] # KeyError
   print fake_var # NameError
   int('a')  # TypeError
   [1,2,3][8]  # IndexError
   import fake # ImportError