More Data Structures, Control Statements,
Functions, and Modules

Sets


In [ ]:
{1,2,3,"bingo"}

In [ ]:
type({1,2,3,"bingo"})

In [ ]:
type({})

In [ ]:
type(set())

In [ ]:
set("spamIam")

Sets have unique elements. They can be compared, differenced, unionized, etc.


In [ ]:
a = set("sp"); b = set("am"); print(a) ; print(b)

In [ ]:
c = set(["a","m"])

In [ ]:
c == b

In [ ]:
"p" in a

In [ ]:
"ps" in a

In [ ]:
q = set("spamIam")
a.issubset(q)

In [ ]:
a | b

In [ ]:
q - (a | b)

In [ ]:
q & (a | b)

Like lists, we can use as (unordered) buckets .pop() gives us a random element


In [ ]:
# this is pretty volitile...wont be the same
# order on all machines
for i in q & (a | b):
    print(i)

In [ ]:
q.remove("a")

In [ ]:
q.pop()

In [ ]:
print(q.pop())
print(q.pop())

In [ ]:
print(q.pop())

In [ ]:
# q.pop()

 

Dictionaries

denoted with a curly braces and colons


In [ ]:
d = {"favorite cat": None, "favorite spam": "all"}

these are key: value, key: value, ...


In [ ]:
print(d["favorite cat"])
d[0]   ## this is not a list and you dont have a keyword = 0

In [ ]:
e = {"favorite cat": None, "favorite spam": "all", \
     1: 'loneliest number'}
e[1] == 'loneliest number'

dictionaries are UNORDERED*.

You cannot assume that one key comes before or after another

* you can use a special type of ordered dict if you really need it:

http://docs.python.org/whatsnew/2.7.html#pep-372-adding-an-ordered-dictionary-to-collections

4 ways to make a Dictionary


In [ ]:
# number 1...you've seen this
d = {"favorite cat": None, "favorite spam": "all"}

In [ ]:
# number 2
d = dict(one = 1, two=2,cat = 'dog') ; print(d)

In [ ]:
# number 3 ... just start filling in items/keys
d = {}  # empty dictionary
d['cat'] = 'dog'
d['one'] = 1
d['two'] = 2
d

In [ ]:
# number 4... start with a list of tuples
mylist = [("cat","dog"), ("one",1),("two",2)]
print(dict(mylist))

In [ ]:
dict(mylist) == d

 

Dictionaries: they can be complicated (in a good way)


In [ ]:
d = {"favorite cat": None, "favorite spam": "all"}

In [ ]:
d = {'favorites': {'cat': None, 'spam': 'all'}, \
     'least favorite': {'cat': 'all', 'spam': None}}
print(d['least favorite']['cat'])

remember: the backslash () allows you to across break lines. Not technically needed when defining a dictionary or list


In [ ]:
phone_numbers = {'family': [('mom','642-2322'),('dad','534-2311')],\
                     'friends': [('Sylvia','652-2212')]}

In [ ]:
for group_type in ['friends','family']:
        print("Group " + group_type + ":")
        for info in phone_numbers[group_type]:
             print(" ",info[0], info[1])

In [ ]:
# this will return a list, but you dont know in what order! 
phone_numbers.keys()

In [ ]:
phone_numbers.values()

 

.keys() and .values(): are called methods on dictionaries


In [ ]:
for group_type in phone_numbers.keys():
        print("Group " + group_type + ":")
        for info in phone_numbers[group_type]:
             print(" ",info[0], info[1])

we cannot ensure ordering here of the groups


In [ ]:
groups = phone_numbers.keys()
groups.sort()
for group_type in groups:
        print("Group " + group_type + ":")
        for info in phone_numbers[group_type]:
             print(" ",info[0], info[1])

.iteritems() is a handy method, returning key,value pairs with each iteration


In [ ]:
for group_type, vals in phone_numbers.iteritems():
        print("Group " + group_type + ":")
        for info in vals:
             print(" ",info[0], info[1])

Some examples of getting values:


In [ ]:
phone_numbers['co-workers']

In [ ]:
phone_numbers.has_key('co-workers')

In [ ]:
print phone_numbers.get('co-workers')

In [ ]:
phone_numbers.get('friends') == phone_numbers['friends']

In [ ]:
print phone_numbers.get('co-workers',"all alone")

 

 

setting values

you can edit the values of keys and also .pop() & del to remove certain keys


In [ ]:
# add to the friends list
phone_numbers['friends'].append(("Jeremy","232-1121"))
print(phone_numbers)

In [ ]:
## Sylvia's number changed
phone_numbers['friends'][0][1] = "532-1521"

In [ ]:
phone_numbers['friends'][0] = ("Sylvia","232-1521"); 
print(phone_numbers['friends'])

In [ ]:
## I lost all my friends preparing for this Python class
phone_numbers['friends'] = [] # sets this to an empty list

In [ ]:
## remove the friends key altogether
print(phone_numbers.pop('friends'))

In [ ]:
print(phone_numbers)

In [ ]:
del phone_numbers['family']

In [ ]:
print(phone_numbers)

 

.update() method is very handy, like .append() for lists


In [ ]:
phone_numbers.update({"friends": [("Sylvia's friend, Dave", "532-1521")]})
print(phone_numbers)

 

Loops and branches in python

Python has the usual control flow statements:

  • if, else, elif
  • for loops
  • while loops
  • break, continue, pass

Indentation in Python defines where blocks begin and end.


In [ ]:
x = 1
    print(x)

IPython Notebook automatically converts tabs into spaces, but some programs do not. Be careful not to mix these up! Be consistent in your programming.

If you're working within the Python interpreter (not the IPython Notebook), you'll see this:

>>> x = 1
>>> if x > 0:
...     print "yo"
... else:
...     print "dude"
... print "ok"
...
yo
ok

In [ ]:
# You can mix indentations between different blocks ... 
# but this is ugly and people will judge you

x = 1
if x > 0:
    print("yo")
else:
        print("dude")

In [ ]:
# You can put everything on one line/statement

print("yo" if x > 0 else "dude")

In [ ]:
# Multiple cases

x = 1
if x < -10:
    print("yo")
elif x > 10:             # 'elif' is short for 'else if'
    print("dude")
else:
    print("sup")

In [ ]:
for x in range(5):
    print(x**2)

In [ ]:
for x in ("all","we","wanna","do","is","eat","your","brains"):
    print(x)

In [ ]:
x = 0
while x < 5:
    print(pow(2,x))
    x += 1             # don't forget to increment x!

In [ ]:
# Multiple levels
for x in range(1,5):
    if x % 2 == 0:
        print(str(x) + " is even.")
    else:
        print(str(x) + " is odd.")

In [ ]:
# Blocks cannot be empty

x = "fried goldfish"
if x == "spam for dinner":
    print("I will destroy the universe")
else:
    AA=1
    # Nothing here.

In [ ]:
# Use a 'pass' statement, which indicates 'do nothing'

x = "fried goldfish"
if x == "spam for dinner":
    print("I will destroy the universe")
else:
    pass

In [ ]:
# Use a 'break' statement to escape a loop

x = 0
while True:
    print(x**2)
    if x**2 > 10:
        break
    x +=1

In [ ]:

What is a Function?

  • A block of organized, reusable code that is used to perform a single, related action.
  • Provides better modularity for your application and a high degree of code reusing.
  • You can name a function anything you want as long as it:
    1. Contains only numbers, letters, underscore
    2. Does not start with a number
    3. Is not the same name as a built-in function (like print).

Basic Synthax of a Function

An Example


In [ ]:
def addnums(x,y):
    return x + y

In [ ]:
addnums(2,3)

In [ ]:
print(addnums(0x1f,3.3))

In [ ]:
print addnums("a","b")

In [ ]:
print addnums("cat",23232)

Scope of a Function


In [ ]:
def numop(x,y):
    x *= 3.14
    return x + y
x = 2
print(numop(x, 8))
print(x)
Python has it’s own local variables list. x is not modified globally ...unless you specify that it’s a global variable

In [ ]:
def numop(x,y):
    x *= 3.14
    global a
    a += 1
    return x + y, a

a = 2
numop(1,1)
numop(1,1)

Pass by reference vs value

All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function.

In [ ]:
def changeme_1( mylist ):
   mylist = [1,2,3,4]; # This would assig new reference in mylist
   print( "Values inside the function changeme_1: ", mylist)
   return

def changeme_2( mylist ):
   mylist.append([1,2,3,4]);
   print( "Values inside the function changeme_2: ", mylist)
   return

mylist1 = [10,20,30];
changeme_1( mylist1 );
print( "Values outside the function: ", mylist1)
print

mylist2 = [10,20,30];
changeme_2( mylist2 );
print( "Values outside the function: ", mylist2)

Function Arguments

You can call a function by using the following types of formal arguments:

  • Required arguments (arguments passed to a function in correct positional order. Here, the number of arguments in the function call should match exactly with the function definition)
  • Keyword arguments (identified by parameter names)
  • Default arguments (assume default values if values are not provided in the function call for those arguments)
  • Variable-length arguments (are not explicitly named in the function definition)

Keyword Arguments


In [ ]:
def numop1(x,y,multiplier=1.0,greetings="Thank you for your inquiry."):
    """ numop1 -- this does a simple operation on two numbers.
     We expect x,y are numbers and return x + y times the multiplier
     multiplier is also a number (a float is preferred) and is optional.
    It defaults to 1.0.
     You can also specify a small greeting as a string. """
    if greetings is not None:
       print(greetings)
    return (x + y)*multiplier

In [ ]:
help(numop1)

In [ ]:
numop1(1,1)

In [ ]:
numop1(1,1,multiplier=-0.5,greetings=None)

Unspecified args and keywords


In [ ]:
def cheeseshop(kind, *arguments, **keywords): 
    print( "-- Do you have any", kind, "?")
    print( "-- I'm sorry, we're all out of", kind )
    for arg in arguments: 
        print( arg)
    print ("-" * 40)
    keys = keywords.keys()
    keys.sort()
    for kw in keys: 
        print (kw, ":", keywords[kw])

In [ ]:
cheeseshop("Limburger", 
           "It's very runny, sir.", 
           "It's really very, VERY runny, sir.",
           shopkeeper='Michael Palin',
           client="John Cleese",
           sketch="Cheese Shop Sketch")

What is a Module?

  • A Python object with arbitrarily named attributes that you can bind and reference.
  • A file consisting of Python code.
  • Allows you to logically organize your Python code.
  • Makes the code easier to understand and use.
  • Can define functions, classes and variables.
  • Can also include runnable code. </UL>
  • Any file ending in .py is treated as a module.
    
    
    In [ ]:
    import math
    
    
    
    In [ ]:
    math.cos(0)
    
    
    
    In [ ]:
    math.cos(math.pi)
    
    
    
    In [ ]:
    math.sqrt(4)
    
    
    
    In [ ]:
    from datetime import datetime
    
    
    
    In [ ]:
    now = datetime.now()
    
    
    
    In [ ]:
    print(now.year, now.month, now.day)
    
    
    
    In [ ]:
    from math import acos as arccos
    
    
    
    In [ ]:
    arccos(1)
    

    Import Statements

    from module_name import name as my_name from module_name import function_name from module_name import variable from module_name import variable, function_name1, function_name2, ... from module_name import *

    Built-In-Modules

    • sys: exposes interpreter stuff & interactions
    • os: exposes platform-specific OS functions
    • math: basic mathematical functions & constants
    • argparse: command line parser
    • datetime: supplies classes for manipulating dates and times
    
    
    In [ ]: