Lecture 11 - Exercises

11A - Docstrings, Preconditions, Postconditions

  1. Which of the following belongs in a function’s docstring? List all that apply.

    1. Preconditions
    2. Postconditions
    3. The steps the function takes to accomplish its task
    4. Information about side-effects the function has
    5. Information about the meaning of the arguments passed to the function
  2. Consider the following function:

    def print_squares(n):
      """ docstring missing! help! """
      i = 0
      while i < n:
        i += 1
        print(i, i**2)
    
      return i**2
    1. Which of the following should be included in the docstring? List all that apply.
      1. The function prints the square of each number from 1 through n

      2. The function uses a while loop

      3. The function returns the square of n

      4. The function returns the square of i

      5. The function uses a counter variable called i

    2. Even with the correct subset of the above, the function could result in an error. Write a precondition that can be included such that as long as the precondition is satisfied, the function cannot cause an error.

11B - Parameters, Local Variables, and Scope

  1. Consider the following program, noticing that several points in the code are marked with comments (e.g., M1). Important: the markers refer to the lines they’re on, not the lines following them.

    # M1
    def a(v1, v2):
        # M2
        v3 = v1 + v2
        # M3
        print(v3)
    
    # M4
    a(4, 6)
    # M5
    1. In which lines (among M1 through M5) is v2 in scope? List all that apply.
    2. In which lines (among M1 through M5) is v3 in scope? List all that apply.
  2. Consider the following program:

    def print_rectangle_area(width, height):
        """ Print the area of a width-by-height
            rectangle. Pre: width and height are numbers. """
    
        area = width * height
        print(area)
    
    w = 4
    h = 3
    a = w * h
    print_rectangle_area(w, h)

    Which of the following could replace the last line of the program and leave its behavior unchanged? List all that apply.

    1. print(h*w)

    2. print(width * height)

    3. print(w * h)

    4. print_rectangle_area(h, w)

  3. What does the following program print?

    def f(x):
        g(3 * x)
    
    def g(x):
        print(x + 2)
    
    f(4)
  4. What does the following program print?

    x = 4
    
    def f(x):
        return 3 * x
    
    def g(x):
        return x + 2
    
    print(f(g(x)))
    print(g(f(x)))

Problems

There are no new Problems for today. Please nominate and vote for problems from past lectures you’d like to go over as a class.