Discussion 1

Links


Concepts

  1. What is the use of an environment diagram? What does it keep track of?
  2. What are the steps to evaluate a def statement?
  3. When executing a call expression, you draw and label a new frame after evaluating the operator and operands. What is the first thing you write inside the new frame?

Problems

Question 1

Fill in the blanks so that cs and 61a alternate printing for a total of n times.

def cs61a(n):
    """
    >>> cs61a(3)
    cs
    61a
    cs
    >>> cs61a(2)
    cs
    61a
    """
    i = 0
    while __________:
        if _________:
            print("cs")
        else:
            print("61a")
        ____________

TOGGLE SOLUTION

def cs61a(n):
    i = 0
    while i < n:
        if i % 2 == 0:
            print("cs")
        else:
            print("61a")
        i += 1

Question 2

Try drawing an environment diagram for this snippet of code from question 2.2 on today’s discussion worksheet:

def outer(n):
    def inner(m):
        return n - m
    return inner

f = outer(10)
f(4)

You can check your work on Python Tutor. We’ll also go over it at the beginning of discussion next week.