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
ifstatement in all cases.To prove this fact, write functions
c,t, andfsuch thatwith_if_statementprints the number 2, butwith_if_functionprints both 1 and 2.
尽管有上述测试,但在所有情况下,此函数实际上并不能实现与 if 语句相同的效果。
为了证明这一事实,请编写函数 c、t 和 f,使得 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 中不是第一个被打印。这说明:
c不是一个print函数,可能只是True或False。- 因此
t和f应该均为print函数。result == None也可以验证这一点。 - 根据打印顺序,
t应为print(1),f应为print(2)。 with_if_statement中未打印1,被跳过,因此c应为False。
def c():
return False
def t():
return print(1)
def f():
return print(2)