Session 3

Functions are your friends


Why do we want to use these things?

Simple programs

Won't always have them.


That's totally fine.

Larger programs

Really need them.

But let's back up

Think about driving directions

Driver's ed taught

 you a few things

Turning the car on/off
Turning left/right

How do I get to the main library?

Your directions

Do you need to tell me...

  • how to cross the road?
  • how to go up stairs?
  • how to turn left/right?

Seems simpler, then

to focus on the important bits of direction instead of basic functional tasks.

        getMetadata(each, wantedheaders),
wantedheaders,"outputdumps/" + filename)

Some actual code

All these functions are custom

...let's not talk about my poor naming conventions.

Can you imagine how long that would be otherwise?

def writeresults(dict,wantedheaders,filename):
    f = open(filename + '.csv','wb')
    w = DictUnicodeWriter(f,wantedheaders)
    for each in dict:
def getMetadata(IDs, headers):
    """Function that takes a list of IDs and metadata values. 
    Returns a dictionary ID: {prop: value}.
    This will populate non-existant values with empty strings.  
    Allows optional properties to be requested."""
    results = {}
    for each in IDs:
        item = ia.Item(each)
        itemresults = {}
        for header in headers:
                itemresults[header] = item.metadata[header]
                itemresults[header] = u''
        results[each] = itemresults
    return results
def printlist(mydict,headers):
    """Function to transform the metadata result dict for output"""
    returnlist = []
    for key, value in mydict.iteritems():
        tempdict = {}
        for each in headers:
            if type(value[each]) == list: 
                tempdict[each] = ":::".join(value[each])
                tempdict[each] = value[each]
    return returnlist

Here are those


Are your eyes bleeding yet?


  • extract complex code out to make your operations easy to understand
    • You have no idea what I'm doing, but you might take a guess that I'm getting metadata and writing it out to a file.  You'd be right.
  • code used in multiple places can be changed in just one place
    • write results is used in 5 places
    • getmetadata in 3
    • and printlist 3

New vocabulary

Defining functions

def sayHello():
    print "hello"


Name of your function


is key

do this stuff...

Calling functions

>>> def sayHello():
...     print "Hello"
>>> sayHello()

Make it do stuff

Passing values

Sometimes you want to do stuff on something that changes

>>> def sayHello(name):
...     print "Hello", name
>>> sayHello("Elizabeth")
Hello Elizabeth

Give the incoming value a variable name

And do stuff with it

Pass a value when you call the function

Return or print

That is the question


Prints a value to the console, but you can't capture the value.

You can use an unlimited number of print statements.


Returns a value within a function.  That value goes away if not captured and dealt with.

You can only have one return statement in a function, and your function exits immediately after evaluating a return statement.

So what?

Ask yourself: do you want to use a value coming out of your function? practice

Our grader code

if grade >= 100:
    result = "A+"
elif grade >= 90:
    result = "A"
elif grade >= 80:
    result = "B"
elif grade >=70:
    result = "C"
elif grade >=60:
    result = "D"
elif grade >= 0:
    result = "F"
    result = "Bad grade"

print result

How can we reuse this code?

What if we had 1,000 grades to process?

Sesson 3

By Elizabeth W.

Sesson 3

  • 832

More from Elizabeth W.