Exercises for Lesson 9
Exercise 1: Writing functions that return values
Part a: Element-wise addition
Write a function that takes in two lists of numbers, and returns a list in which each value is the sum of the two corresponding input values. You can assume both input lists have the same length.
Here is an example output from this program:
>>> firstList = [1,2,3,4]
>>> secondList = [8,2,6,1]
>>> sumList = perElementAddition(firstList, secondList)
>>> print(sumList)
[9, 4, 9, 5]
Here is your function to define:
def perElementAddition(list1, list2):
"""
Returns the per-element sum of the two lists.
list1: a list of numbers
list2: a list of numbers of the same length as list1
returns: a list of the per-element totals (a list of numbers)
"""
# TODO
Part b: What’s in a name?
Now, let’s discuss the following function, and some code that uses it.
def cube(x):
answer = x * x * x
return answer
Think carefully about what this code does. Now let’s see it in use.
>>> answer = 4
>>> result = cube(3)
>>> print(answer, result)
4 27
Why did it print 4 27
and not 27 27
?
Exercise 2: Functions that return multiple values
Read through the following code:
def sumDiff(x, y):
total = x + y
diff = x - y
return total, diff
def main():
valString = input("Please enter two numbers, separated by a comma: ")
vals = valString.split(',')
numStr1, numStr2 = vals # "unpack" the values of the list
num1 = float(numStr1)
num2 = float(numStr2)
resultVals = sumDiff(num1, num2)
total, diff = resultVals # unpack again
print("The sum is {0} and the difference is {1}".format(total, diff))
main()
Let’s say the user enters “7,3”. What do you expect the output to be?
What would happen if the return
line at the end of sumDiff
weren’t there?
Exercise 3: Modifying function parameters
The following function converts a temperature in degrees Celsius to the temperate in Fahrenheit.
def convertToFahrenheit(celsiusTemp):
return 9/5 * celsiusTemp + 32
Write a function that takes in a list of temperatures in Celsius and modifies that list, converting each temperature to its corresponding value in Fahrenheit. It does not need to return anything.
def convertListToFahrenheit(tempList):
# TODO
Exercise 4: True and False
For each of the following code snippets, predict what will be printed.
a) >>> 3 < 4
b) >>> 3 >= 4
c) >>> 3 != 4
d) >>> 3 == 4
e) >>> "hello" == "hello"
f) >>> "hello" < "hello"
g) >>> "Hello" < "Hello"
Exercise 5: Input validation
Up until now, we’ve assumed that users provide the type of input we want. Add error checking to the following function.
from graphics import *
def main():
# Get the number of points from the user
n = int(input("How many points would you like? "))
# Make the window
win = GraphWin("A shape with " + str(n) + " points", 800, 600)
# Get the points
points = []
for i in range(n):
p = win.getMouse()
points.append(p)
p.draw(win)
# Draw the polygon
polygon = Polygon(points)
polygon.setFill("forest green")
polygon.draw(win)
main()
Exercise 6: Two-way decisions
For each of the following code snippets, predict what will be printed.
>>> x = 10
>>> y = 12
>>> z = 4
a) if x > 10:
print("yes")
else:
print("no")
b) if x == y:
print("yep")
else:
print("nope")
c) if z * 3 < y:
print("si")
else:
print("no")