Skip to content

Problem 4: If Function vs Statement (100pts)

Problem

def if_function(condition, true_result, false_result):
    """Return true_result if condition is a true value, and
    false_result otherwise.

    >>> if_function(True, 2, 3)
    2
    >>> if_function(False, 2, 3)
    3
    >>> if_function(3==2, 3+2, 3-2)
    1
    >>> if_function(3>2, 3+2, 3-2)
    5
    """
    if condition:
        return true_result
    else:
        return false_result

Despite the doctests above, this function actually does not do the same thing as an if statement in all cases.

To prove this fact, write functions c, t, and f such that with_if_statement prints the number 2, but with_if_function prints both 1 and 2.

尽管有上述测试,但在所有情况下,此函数实际上并不能实现与 if 语句相同的效果。

为了证明这一事实,请编写函数 ctf,使得 with_if_statement 打印数字 2,但 with_if_function 打印 1 和 2。

def with_if_statement():
    """
    >>> result = with_if_statement()
    2
    >>> print(result)
    None
    """
    if c():
        return t()
    else:
        return f()


def with_if_function():
    """
    >>> result = with_if_function()
    1
    2
    >>> print(result)
    None
    """
    return if_function(c(), t(), f())


def c():
    "*** YOUR CODE HERE ***"


def t():
    "*** YOUR CODE HERE ***"


def f():
    "*** YOUR CODE HERE ***"

Hints

Hint: If you are having a hard time identifying how an if statement and if_function differ, consider the rules of evaluation for if statements and call expressions.

  • 如果您在区分 if 语句和 if_function 的不同之处时遇到困难,请考虑回顾 if 语句的求值规则调用表达式的求值规则

  • if 语句中,t()f() 只会执行一个

  • 调用函数时,t()f() 都会被执行

  • 注意:不是打印 2 和 1。如果你的反过来了,想想是不是 c() 写错了

  • print() 的返回值是 None

Solutions

运行这两个函数时,我们没有使用 print,却打印出了消息,这说明我们调用的函数有副作用,可以推测,三个函数中有两个为 print 函数。

观察两次输出,我们发现:2 均被打印,但在 with_if_function 中不是第一个被打印。这说明:

  1. c 不是一个 print 函数,可能只是 TrueFalse
  2. 因此 tf 应该均为 print 函数。result == None 也可以验证这一点。
  3. 根据打印顺序,t 应为 print(1)f 应为 print(2)
  4. with_if_statement 中未打印 1,被跳过,因此 c 应为 False
def c():
    return False

def t():
    return print(1)

def f():
    return print(2)