💻hw01
Q5: If Function vs Statement
Let's try to write a function that does the same thing as an if statement.
defif_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():
"""
>>> result = with_if_statement()
47
>>> print(result)
None
"""
if cond():
return true_func()
else:
return false_func()
//if cond()is True, then only call true_func(), false_func()will not be called
def with_if_function():
"""
>>> result = with_if_function()
42
47
>>> print(result)
None
// 说明:no return 或者 return None
"""
return if_function(cond(), true_func(), false_func())
//在call if_function前,得先call c(),t(),f()(打印42,47),把返回值传入formal paramater -> ( *** , None, None)->所以,if_func返回的是None ->result = None
//call expression会执行嵌套的函数;而if仅当条件满足时才会执行
def cond():
"*** YOUR CODE HERE ***"
return False
def true_func():
"*** YOUR CODE HERE ***"
print(42)
def false_func():
"*** YOUR CODE HERE ***"
print(47)
Q1: f = max -> max(2,3) = f(2,3)
赋值语句也可以用于给函数一个名字(eg,f)
强大的python,a-b = sub(a,b) ,f = sub -> a-b == f(a,b)