Control

发布时间 2024-01-03 20:05:31作者: viewoverlook

Control

区分python中两种类型的函数

  • 纯函数(pure functions): 函数中有一些输入(参数)并返回一些输出(调用返回结果)
abs(-2)

可将内置函数abs描述为接受输入并产生输出的小型机器

abs在调用时除了返回值外不会造成其他任何影响,而且使用相同参数调用时总会返回相同的值

  • 非纯函数(Non-pure functions): 除了返回值外,调用一个非纯函数还会产生其他改变解释器和计算机状态的副作用(side effect)。一个常见的副作用就是使用print函数产生(非返回值的)额外输出
print(1,2,3)
```ad-summary 虽然print和abs在上述例子中相似,但是工作方式不同,print返回值始终为None,不代表任何内容的特殊python值。交互式python解释器不会自动打印。 ```

以下这个例子显示print的嵌套表达式展示非纯函数的特征

print(print(1),print(2))
小心使用print!他返回的None意味着其不应该用于赋值语句

纯函数不能有副作用,或是随着时间推移的改变的限制,但是对其施加这些限制会产生巨大的好处。首先,纯函数可以更可靠地组成复合调用表达式。在上面的示例中可以看到在操作数表达式中使用非纯函数 print 并不能返回有用的结果,但另一方面,我们已经看到 max, pow, sqrt 等函数可以在嵌套表达式中有效使用。

第二,纯函数往往更易于测试。相同的参数列表会返回相同的值,我们可以将其与预期的返回值进行比较。本章后面将更详细地讨论测试。

第三,第四章将说明纯函数对于编写可以同时计算多个调用表达式的并发程序来说是必不可少的。

此外,第二章会研究一系列非纯函数并描述它们的用途。

所以我们将在本章的剩余部分重点介绍纯函数的创建和使用,print 函数仅用于查看计算的中间结果。

Miscellaneous Python Features

文档

函数定义通常包括描述函数的文档,称为 “文档字符串 docstring”,它必须在函数体中缩进。文档字符串通常使用三个引号,第一行描述函数的任务,随后的几行可以描述参数并解释函数的意图:

>>> def pressure(v, t, n):
        """计算理想气体的压力,单位为帕斯卡

        使用理想气体定律:http://en.wikipedia.org/wiki/Ideal_gas_law

        v -- 气体体积,单位为立方米
        t -- 绝对温度,单位为开尔文
        n -- 气体粒子
        """
        k = 1.38e-23  # 玻尔兹曼常数
        return n * k * t / v

当你使用函数名称作为参数调用 help 时,你会看到它的文档字符串(键入 q 以退出 Python help)。

>>> help(pressure)

注释:Python 中的注释可以附加到 # 号后的行尾。例如,上面代码中的注释 玻尔兹曼常数 描述了 k 变量的含义。这些注释不会出现在 Python 的 help 中,而且会被解释器忽略,它们只为人类而存在。

参数默认值

定义通用函数的结果是引入了额外的参数。具有许多参数的函数可能调用起来很麻烦并且难以阅读。

在 Python 中,我们可以为函数的参数提供默认值。当调用该函数时,具有默认值的参数是可选的。如果未提供,则将默认值绑定到形参上。例如,如果程序通常用于计算 “一摩尔” 粒子的压力,则可以提供此值作为默认值:

>>> def pressure(v, t, n=6.022e23):
        """计算理想气体的压力,单位为帕斯卡

        使用理想气体定律:http://en.wikipedia.org/wiki/Ideal_gas_law

        v -- 气体体积,单位为立方米
        t -- 绝对温度,单位为开尔文
        n -- 气体粒子,默认为一摩尔
        """
        k = 1.38e-23  # 玻尔兹曼常数
        return n * k * t / v
=在这里有两种含义,def中不表示赋值,而是指示函数调用时的默认值。
函数体中k的赋值语句将名称k与玻尔兹曼常数的近似值进行了绑定。

Designing Functions

函数是所有程序(无论大小)的基本组成部分,并且是我们使用编程语言来表达计算过程的主要媒介。之前我们已经讨论过了函数的形式及其调用方式,而本节我们将讨论 “什么是一个好函数”。从根本上说,好函数共有的品质就是:它们都强化了“函数就是抽象” 的理念。

  • 每个函数应该只负责一个任务,且该任务要用一个简短的名称来识别,并在一行文本中进行描述。按顺序执行多个任务的函数应该分为多个函数。
  • 不要重复自己(Don't repeat yourself)是软件工程的核心原则。这个所谓的 DRY 原则指出,多个代码片段不应该描述重复的逻辑。相反,逻辑应该只实现一次,为其指定一个名称后多次使用。如果你发现自己正在复制粘贴一段代码,那么你可能已经找到了进行函数抽象的机会。
  • 定义通用的函数。比如作为 pow 函数的一个特例的平方函数就不在 Python 库中,因为 pow 函数可以将数字计算为任意次方。

这些准则提高了代码的可读性,减少了错误的数量,并且通常最大限度地减少了编写的代码总量。将复杂的任务分解为简洁的功能是一项需要经验才能掌握的技能。幸运的是,Python 提供了多种特性来支持你的工作。

注意hw01中有一道题涉及函数与if语句的区别,我觉得那个非常好,最后实现方法是利用if语句只判断一下二选一,但是函数需要评估所有的参数。例如以下:cond()是False,在if_statement中先判断False,然后执行if_else中的一个,但是在if_function中我们把True条件改变就可以轻而易举的做到cond()的选择效果不起作用
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, 'equal', 'not equal')

    'not equal'

    >>> if_function(3>2, 'bigger', 'smaller')

    'bigger'

    """

    if condition:

        return true_result

    else:

        return false_result

  
  

def with_if_statement():

    """

    >>> result = with_if_statement()

    61A

    >>> print(result)

    None

    """

    if cond():

        return true_func()

    else:

        return false_func()

  
  

def with_if_function():

    """

    >>> result = with_if_function()

    Welcome to

    61A

    >>> print(result)

    None

    """

    return if_function(cond(), true_func(), false_func())

  
  

def cond():

    "*** YOUR CODE HERE ***"

    global x

    x=1

    if x==1:

        return False

    else:

        return True

  
  

def true_func():

    "*** YOUR CODE HERE ***"

    global x

    x=2

    if x==2:

        print("Welcome to")

  

def false_func():

    "*** YOUR CODE HERE ***"

    global x

    x=1

    if x==1:

        print("61A")

Discussion 1 | CS 61A Spring 2021

Conditional statements

Conditional statements let programs execute different lines of code depending on certain conditions. Let’s review the if-elif-else syntax.

Recall the following points:

  • The else and elif clauses are optional, and you can have any number of elif clauses.

  • conditional expression is an expression that evaluates to either a truthy value (True, a non-zero integer, etc.) or a falsy value (False0None""[], etc.).

  • Only the suite that is indented under the first if/elif whose conditional expression evaluates to a true value will be executed.

  • If none of the conditional expressions evaluate to a true value, then the else suite is executed. There can only be one else clause in a conditional statement!

    if :
    ;
    elif :
    ;
    else:
    ;

Boolean Operators

Python also includes the boolean operators andor, and not. These operators are used to combine and manipulate boolean values.

  • not returns the opposite truth value of the following expression (so not will always return either True or False).

  • and evaluates expressions in order and stops evaluating (short-circuits) once it reaches the first false value, and then returns it. If all values evaluate to a true value, the last value is returned.

  • or short-circuits at the first true value and returns it. If all values evaluate to a false value, the last value is returned.

    not None
    True
    not True
    False
    -1 and 0 and 1
    0
    False or 9999 or 1/0
    9999