CS61A-L2andHw

文章探讨了Python中如何使用自定义函数模拟if语句的行为,并通过示例展示了函数调用与条件语句在执行上的差异。if_function函数接受条件及对应结果作为参数,根据条件返回结果。相比之下,if语句仅在条件满足时执行相关代码。文章还提到了函数赋值以及函数调用的副作用。
摘要由CSDN通过智能技术生成

💻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)

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值