Skip to main content

Section 8.3 Evaluate Functions

Subgoals for evaluating a function call:.

  1. Create stack frame for global variables
  2. Ensure function is defined before function call before beginning body of function
  3. Determine parameter values based on positional arguments, keyword arguments, and default values to initialize local variables
  4. Use stack frame for function to trace local variables
  5. At return to call site, pass values back to call site
  6. Delete stack frame with local variables after return to call site

Subsection 8.3.1 Simple Call

  • One argument
  • No arguments
  • Two arguments
def foo(alpha, beta, gamma):
    delta = alpha * beta - gamma
    return delta * 2

alpha = 9
kappa = foo(7, alpha, 1)
gamma = kappa + 1

Subsection 8.3.2 Keyword Arguments

def subtract(a, b, c=1):
    return a*c - b

# P1
print(subtract(a=7, b=9))
# P2
print(subtract(b=7, a=9))
# P3
print(subtract(7, b=5))
# P4
print(subtract(10, 5, 2))
# P5
print(subtract(c=2, b=5, a=10))
# P6
print(subtract(100, 50, c=.1))

Subsection 8.3.3 Nested Calls

def add5(number):
    number = number + 5
    return number

def double(num):
    result = num * 2
    num = num + 1 # Have this useless thing in there at least once
    return result

answer = 10
# One with assignments
answer = add5(answer)
answer = double(answer)
print(answer)
# One without assignments
add5(answer)
double(answer)
print(answer)
# Nested
print(add5(double(answer)))

Subsection 8.3.4 Calls within Calls

        # Example
def third(value):
    result = round(value/3)
    return result

def chop_third(text):
    result = text
    length = third(len(result))
    result = text[:length]
    return result

print(chop_third("something"))
# P1
def is_month(value):
    result = value > 0
    result = result and value <= 12
    return result

def is_day(value):
    result = value > 0 and value <= 31
    return result

def is_date(day, month):
    result = is_day(day) and is_month(month)
    return result

print(is_date(1, 30))
print(is_date(30, 1))
# P2
def a(x, y=1):
    z = 3
    x = x * 2
    return x + y + z

def b(x, z):
    y = 3
    z = z + z
    return x + y + z

def c(x, y, z):
    x = a(x, y)
    y = z(z, y)
    z = a(x) - y
    return x + y + z

print(c(1, 2, 3))
You have attempted of activities on this page.