Exercises for Lesson 7

Back to Lesson 7

Exercise 1: 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

Back to Lesson 7

Exercise 2: Writing functions that return values

Part a: Working with lists

Implement the following functions. Remember that you can use [] for indexing and slicing operations.

def getMiddleElement(lst):
    """
    Returns the middle element from a list.  Rounds down if even length.

    lst: a list
    returns: a single element at the middle position of lst
    """
    # TODO
def getOutside(lst):
    """
    Returns the concatentation of the first and last strings in a list.

    lst: a list of strings (assume its length is at least 2)
    returns: the first and last strings, concatenated together (a string)
    """
    # TODO
def getInnerList(lst):
    """
    Returns a list that is missing its first and last elements.

    lst: a list (assume its length is at least 2)
    returns: the inner part of lst, without the first and last elements (a list)
    """
    # TODO

Here is an example of how these could be used:

mylist = ["apple", 3.14, 111, "dog"]
res1a = getMiddleElement(mylist)      # 3.14
res1b = getMiddleElement(mylist[1:])  # 111
print(res1a, res1b, mylist)           # 3.14 111 ['apple', 3.14, 111, 'dog']

res2 = getOutside(lst)    # "appledog"
res3 = getInnerList(lst)  # [3.14, 111]
print(res2, res3, mylist) # appledog [3.14, 111] ['apple', 3.14, 111, 'dog']

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.

If you want to build a list as you go, you can create an empty list and then append items to it:

mylist = []          # empty list
mylist.append(1)     # now [1]
mylist.append("bat") # now [1, "bat"]

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

Back to Lesson 7

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"

Back to Lesson 7

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")
elif y > z:
    print("maybe?")
else:
    print("nope")

# (c)
if z * 3 <= y:
    print("sí")
else:
    print("no")

Back to Lesson 7

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?

Back to Lesson 7

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

Back to Lesson 7