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 def with_if_statement(): """ >>> with_if_statement() 1 """ if c(): return t() else: return f() def with_if_function(): return if_function(c(), t(), f())
To do this, you must write three functions: c , t and f such that with_if_statement returns 1 , and with_if_function does not return 1 (and can do anything else)
In the beginning, the problem seems ridiculous, since logically with_if_statement and with_if_function same. However, if we see these two functions from the view of the interpreter, they are different.
The with_if_function function uses a call expression that ensures that all of its subexpressions of the operands are evaluated before the if_function is applied to the received arguments. Therefore, even if c returns False , the t function is called. In contrast, with_if_statement will never call t if c returns False (this paragraph from the UCB site).
def c(): return True def t(): return 1 def f(): '1'.sort()
source share