Lectures 5 & 6: FunctionsΒΆ

Based on the lecture and the readings (R&S Functions) you should be able to:

  • Identify how to define and call functions

  • Understand scoping.

Below, please find some practice problems for this topic. These problems should be completed by hand. You can check your answers using the files in lpp/lec5-6 in your repository. (Run git pull upstream master to pick up these files.)

  1. Write the code necessary to complete the following function.

def check_number_order(num_list):
  '''
  Purpose: given a list of three numbers (n1, n2, and n3), check
    that n1 < n2 < n3. Return the boolean for whether this order is
    preserved.

  Inputs:
    num_list (list): a list of three numbers (int or float)

  Returns (boolean): return True if the values are in order, False
  otherwise.
  '''
  1. Explain what this function does in plain English.

def mystery(number_list):
    ''' Why knows ... '''
    count = 0
    for num in number_list:
        if num < 0:
            count += 1
    return count
  1. What is the output of call_mystery:

def mystery(l):
    ''' Why knows ... '''
    rv = []
    for x in l:
        rv = [x] + rv
    return rv

def call_mystery():
    ''' Runs mystery function ... '''
    print("Warmup exercise 2:")
    l = [0, 1, 2, 3, 4]
    nl = mystery(l)
    print("l: ", l)
    print("nl: ", nl)
  1. Explain what this function does in plain English.

def mystery(list1):
    start_val = 0
    rl = []
    i = -1
    for i in list1:
        if i > start_val:
            i = start_val
    for j in list1:
        if j >= i - 100:
            rl.append(j)
    return rl
  1. What is the output of the following code:

def F1(i, j) :
    print("F1({}, {})".format(i, j))
    F2(j, i+j)
    print("F1: i = {}, j = {}".format(i, j))


def F2(i, j) :
    print("    F2({}, {})".format(i, j))
    k = F3(i, j)
    print("    F2: i = {}, j = {}, k = {}".format(i, j, k))


def F3(i, j) :
    print("        F3({}, {})".format(i, j))
    i = i+j
    j = i+2*j
    k = 2*i+3*j
    print("        F3: i = {}, j = {}, k = {}".format(i, j, k))
    return k

 print("Warmup exercise 1:")
 F1(1, 1)
 print()
  1. (Challenge exercise): What is the output of the following code?

def mystery3(l):
    n = len(l)
    for i in range(n // 2):
        t = l[i]
        l[i] = l[n-i-1]
        l[n-i-1] = t

print("Challenge exercise:")
l = [0, 1, 2, 3, 4]
mystery3(l)
print("l: ", l)