Week 1: 1 The Python Programming Language: Functions
Week 1: 1 The Python Programming Language: Functions
June 3, 2020
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.
add_numbers(1, 3)
In [ ]: 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))
print(add_numbers(1, 2, flag=True))
1
Assign function add_numbers to variable a.
In [ ]: def add_numbers(x,y):
return x+y
a = add_numbers
a(1,2)
In [ ]: type('This is a string')
In [ ]: type(None)
In [ ]: type(1)
In [ ]: type(1.0)
In [ ]: type(add_numbers)
In [ ]: x.append(3.3)
print(x)
In [ ]: for item in x:
print(item)
In [ ]: i=0
while( i != len(x) ):
print(x[i])
i = i + 1
In [ ]: [1,2] + [3,4]
2
Use * to repeat lists.
In [ ]: [1]*3
In [ ]: 1 in [1, 2, 3]
In [ ]: 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
In [ ]: x[-1]
This will return the slice starting from the 4th element from the end and stopping before the
2nd element from the end.
In [ ]: x[-4:-2]
This is a slice from the beginning of the string and stopping before the 3rd element.
In [ ]: x[:3]
And this is a slice starting from the 4th element of the string and going all the way to the end.
In [ ]: x[3:]
In [ ]: firstname = 'Christopher'
lastname = 'Brooks'
split returns a list of all the words in a string, or a list split on a specific character.
In [ ]: firstname = 'Christopher Arthur Hansen Brooks'.split(' ')[0] # [0] selects the first ele
lastname = 'Christopher Arthur Hansen Brooks'.split(' ')[-1] # [-1] selects the last ele
print(firstname)
print(lastname)
In [ ]: 'Chris' + 2
In [ ]: 'Chris' + str(2)
3
Dictionaries associate keys with values.
In [ ]: for name in x:
print(x[name])
In [ ]: fname
In [ ]: lname
Make sure the number of values you are unpacking matches the number of variables being
assigned.
In [ ]: print('Chris' + 2)
In [ ]: print('Chris' + str(2))
4
In [ ]: sales_record = {
'price': 3.24,
'num_items': 4,
'person': 'Chris'}
print(sales_statement.format(sales_record['person'],
sales_record['num_items'],
sales_record['price'],
sales_record['num_items']*sales_record['price']))
In [ ]: import csv
%precision 2
csv.Dictreader has read in each row of our csv file as a dictionary. len shows that our list is
comprised of 234 dictionaries.
In [ ]: len(mpg)
In [ ]: 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.
5
Similarly this is how to find the average hwy fuel economy across all cars.
Use set to return the unique values for the number of cylinders the cars in our dataset have.
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.
In [ ]: CtyMpgByCyl = []
CtyMpgByCyl.sort(key=lambda x: x[0])
CtyMpgByCyl
Use set to return the unique values for the class types in our dataset.
And here’s an example of how to find the average hwy mpg for each class of vehicle in our
dataset.
In [ ]: HwyMpgByClass = []
HwyMpgByClass.sort(key=lambda x: x[1])
HwyMpgByClass
6
In [ ]: import datetime as dt
import time as tm
time returns the current time in seconds since the Epoch. (January 1st, 1970)
In [ ]: tm.time()
In [ ]: dtnow = dt.datetime.fromtimestamp(tm.time())
dtnow
In [ ]: today = dt.date.today()
In [ ]: class Person:
department = 'School of Information' #a class variable
In [ ]: person = Person()
person.set_name('Christopher Brooks')
person.set_location('Ann Arbor, MI, USA')
print('{} live in {} and works in the department {}'.format(person.name, person.location
7
Now let’s iterate through the map object to see the values.
In [ ]: my_function = lambda a, b, c : a + b
In [ ]: my_function(1, 2, 3)
In [ ]: my_list = []
for number in range(0, 1000):
if number % 2 == 0:
my_list.append(number)
my_list
In [ ]: import numpy as np
## Creating Arrays
Create a list and convert it to a numpy array
In [ ]: mylist = [1, 2, 3]
x = np.array(mylist)
x
In [ ]: y = np.array([4, 5, 6])
y
Use the shape method to find the dimensions of the array. (rows, columns)
In [ ]: m.shape
8
In [ ]: n = np.arange(0, 30, 2) # start at 0 count up by 2, stop before 30
n
reshape returns an array with the same data with a new shape.
In [ ]: o.resize(3, 3)
o
ones returns a new array of given shape and type, filled with ones.
In [ ]: np.ones((3, 2))
zeros returns a new array of given shape and type, filled with zeros.
In [ ]: np.zeros((2, 3))
eye returns a 2-D array with ones on the diagonal and zeros elsewhere.
In [ ]: np.eye(3)
In [ ]: np.diag(y)
In [ ]: np.array([1, 2, 3] * 3)
In [ ]: np.repeat([1, 2, 3], 3)
In [ ]: np.vstack([p, 2*p])