Introductiontocourse: 1 The Python Programming Language: Functions
Introductiontocourse: 1 The Python Programming Language: Functions
You are currently looking at version 1.1 of this notebook. To download notebooks and datafiles, as well
as get help on Jupyter notebooks in the Coursera platform, visit the Jupyter Notebook FAQ course resource.
[1]: x = 1
y = 2
x + y
[1]: 3
[2]: y
[2]: 2
add_numbers is a function that takes two numbers and adds them together.
[3]: def add_numbers(x, y):
return x + y
add_numbers(1, 2)
[3]: 3
‘add_numbers’ updated to take an optional 3rd parameter. Using print allows printing of
multiple expressions within a single cell.
[4]: def add_numbers(x,y,z=None):
if (z==None):
return x+y
else:
return x+y+z
print(add_numbers(1, 2))
print(add_numbers(1, 2, 3))
3
6
1
add_numbers updated to take an optional flag parameter.
[5]: def add_numbers(x, y, z=None, flag=False):
if (flag):
print('Flag is true!')
if (z==None):
return x + y
else:
return x + y + z
print(add_numbers(1, 2, flag=True))
Flag is true!
3
Assign function add_numbers to variable a.
[6]: def add_numbers(x,y):
return x+y
a = add_numbers
a(1,2)
[6]: 3
2
[13]: x = [1, 'a', 2, 'b']
type(x)
[13]: list
Use append to append an object to a list.
[14]: x.append(3.3)
print(x)
1
a
2
b
3.3
1
a
2
b
3.3
3
[20]: x = 'This is a string'
print(x[0]) #first character
print(x[0:1]) #first character, but we have explicitly set the end character
print(x[0:2]) #first two characters
T
T
Th
Christopher Brooks
ChristopherChristopherChristopher
True
split returns a list of all the words in a string, or a list split on a specific character.
[26]: firstname = 'Christopher Arthur Hansen Brooks'.split(' ')[0] # [0] selects the␣
,→first element of the list
print(firstname)
print(lastname)
Christopher
Brooks
4
Make sure you convert objects to strings before concatenating.
[27]: 'Chris' + 2
␣
,→ ---------------------------------------------------------------------------
<ipython-input-27-9d01956b24db> in <module>
----> 1 'Chris' + 2
[ ]: 'Chris' + str(2)
Dictionaries associate keys with values.
[ ]: x = {'Christopher Brooks': '[email protected]', 'Bill Gates': 'billg@microsoft.
,→com'}
␣
,→---------------------------------------------------------------------------
<ipython-input-28-54a8dcce786c> in <module>
1 for name in x:
----> 2 print(x[name])
5
[ ]: for email in x.values():
print(email)
Iterate over all of the items in the list:
[ ]: for name, email in x.items():
print(name)
print(email)
You can unpack a sequence into different variables:
[ ]: x = ('Christopher', 'Brooks', '[email protected]')
fname, lname, email = x
[ ]: fname
[ ]: lname
Make sure the number of values you are unpacking matches the number of variables being
assigned.
[ ]: x = ('Christopher', 'Brooks', '[email protected]', 'Ann Arbor')
fname, lname, email = x
[33]: print('Chris' + 2)
␣
,→---------------------------------------------------------------------------
<ipython-input-33-928a1e955b60> in <module>
----> 1 print('Chris' + 2)
Chris2
6
'person': 'Chris'}
print(sales_statement.format(sales_record['person'],
sales_record['num_items'],
sales_record['price'],
sales_record['num_items']*sales_record['price']))
%precision 2
␣
,→ ---------------------------------------------------------------------------
<ipython-input-29-9d52614e743e> in <module>
3 get_ipython().run_line_magic('precision', '2')
4
----> 5 with open('mpg.csv') as csvfile:
7
6 mpg = list(csv.DictReader(csvfile))
7
csv.Dictreader has read in each row of our csv file as a dictionary. len shows that our list is
comprised of 234 dictionaries.
[ ]: len(mpg)
keys gives us the column names of our csv.
[ ]: mpg[0].keys()
This is how to find the average cty fuel economy across all cars. All values in the dictionaries
are strings, so we need to convert to float.
[ ]: sum(float(d['cty']) for d in mpg) / len(mpg)
Similarly this is how to find the average hwy fuel economy across all cars.
[ ]: sum(float(d['hwy']) for d in mpg) / len(mpg)
Use set to return the unique values for the number of cylinders the cars in our dataset have.
[30]: cylinders = set(d['cyl'] for d in mpg)
cylinders
␣
,→---------------------------------------------------------------------------
<ipython-input-30-3bcce509dbc3> in <module>
----> 1 cylinders = set(d['cyl'] for d in mpg)
2 cylinders
Here’s a more complex example where we are grouping the cars by number of cylinder, and
finding the average cty mpg for each group.
[ ]: CtyMpgByCyl = []
8
if d['cyl'] == c: # if the cylinder level type matches,
summpg += float(d['cty']) # add the cty mpg
cyltypecount += 1 # increment the count
CtyMpgByCyl.append((c, summpg / cyltypecount)) # append the tuple␣
,→('cylinder', 'avg mpg')
CtyMpgByCyl.sort(key=lambda x: x[0])
CtyMpgByCyl
Use set to return the unique values for the class types in our dataset.
[ ]: vehicleclass = set(d['class'] for d in mpg) # what are the class types
vehicleclass
And here’s an example of how to find the average hwy mpg for each class of vehicle in our
dataset.
[ ]: HwyMpgByClass = []
HwyMpgByClass.sort(key=lambda x: x[1])
HwyMpgByClass
[ ]: import datetime as dt
import time as tm
time returns the current time in seconds since the Epoch. (January 1st, 1970)
[31]: tm.time()
␣
,→---------------------------------------------------------------------------
<ipython-input-31-f6000a133ef6> in <module>
9
----> 1 tm.time()
10
[32]: for item in cheapest:
print(item)
␣
,→ ---------------------------------------------------------------------------
<ipython-input-32-d5907a436dfb> in <module>
----> 1 for item in cheapest:
2 print(item)
11