Functions are your friends
That's totally fine.
Turning the car on/off
Turning left/right
Stopping...starting...parking...
Do you need to tell me...
writeresults(
printlist(
getMetadata(each, wantedheaders),
wantedheaders),
wantedheaders,"outputdumps/" + filename)
All these functions are custom
...let's not talk about my poor naming conventions.
def writeresults(dict,wantedheaders,filename):
f = open(filename + '.csv','wb')
f.write(u'\ufeff'.encode('utf8'))
w = DictUnicodeWriter(f,wantedheaders)
w.writeheader()
for each in dict:
w.writerow(each)
f.close()
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:
try:
itemresults[header] = item.metadata[header]
except:
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])
else:
tempdict[each] = value[each]
returnlist.append(tempdict)
return returnlist
Here are those
functions
Are your eyes bleeding yet?
def sayHello():
print "hello"
Python
keyword
Name of your function
Punctuation
is key
do this stuff...
>>> def sayHello():
... print "Hello"
...
>>> sayHello()
Hello
Make it do stuff
>>> 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
print
Prints a value to the console, but you can't capture the value.
You can use an unlimited number of print statements.
return
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.
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"
else:
result = "Bad grade"
print result