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