Exercises for Lesson 9
Exercise 1: Writing functions that return values
Part a: Working with strings
Implement the following functions.
def getMiddleChar(s):
"""
Returns the middle character from a string. Rounds down if even length.
s: a string
returns: a single character at the middle position of s (a string)
"""
# TODO
def getOutside(s):
"""
Returns the concatentation of the first and last characters in a string.
s: a string (assume its length is at least 2)
returns: the first and last characters, concatenated together (a string)
"""
# TODO
def getInnerString(s):
"""
Returns a string that is missing its first and last characters.
s: a string (assume its length is at least 2)
returns: the inner part of s, without the first and last characters (a string)
"""
# TODO
Here is an example of how these could be used:
s = "pineapple"
res1a = getMiddleChar(s)
res1b = getMiddleChar("pine")
print(res1a, res1b) # what does this give?
res2 = getOutside(s)
res3 = getInnerString(s)
print(res2, res3) # what about this one?
Part b: 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) # prints: [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
Exercise 2: What’s in a name? (variable scope)
Now, let’s discuss the following function, and some code that uses it.
def cube(x):
answer = x * x * x
return answer
Why does the following code print 4 27
and not 27 27
?
answer = 4
result = cube(3)
print(answer, result) # prints: 4 27
Exercise 3: True and False
For each of the following expressions, 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"
h) "hello" < "Hello"
Exercise 4: 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")
Exercise 5: 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, this time from the resulting tuple
print("The sum is", total, "and the difference is", 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 6: 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 7: Input validation
Up until now, we’ve assumed that users provide the type of input we want. Add error checking to the following function. In your modified version, the program should just return from main
early if the user types anything 2
or smaller for n
.
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()