提交 d1bc2159 编写于 作者: W wizardforcel

2.6.

上级 20d9a37b
# Organizing your code with functions
# 使用函数组织你的代码
<img src="img/pestle.png" width="75" align="right">Years ago I learned to make Thai red curry paste from scratch, including roasting then grinding seeds and pounding stuff in a giant mortar and pestle. It takes forever and so I generally buy curry paste ready-made from the store.
<img src="img/pestle.png" width="75" align="right">
<img src="img/redcurry.jpeg" width="70" align="right">Similarly, most cookbooks provide a number of fundamental recipes, such as making sauces, that are used by other recipes. A cookbook is organized into a series of executable recipes, some of which "invoke" other recipes. To make dinner, I open a cookbook, acquire some raw ingredients, then execute one or more recipes, usually in a specific sequence.
几年前,我学会了从头开始制作泰国红咖喱酱,包括烘烤,然后在巨大的研钵和杵中研磨和捣碎种子。这需要很长时间,所以我一般都会从商店购买现成的咖喱酱。
Writing a program proceeds in the same way. Opening a cookbook is the same as importing libraries. Acquiring raw ingredients could mean loading data into the memory. The main program invokes functions (recipes) to accomplish a particular task. As part of writing a program, we will typically break out logical sections of code into functions specific to our problem, whereas the functions in libraries tend to be broadly-applicable.
<img src="img/redcurry.jpeg" width="70" align="right">
The way we organize our code is important. Programs quickly become an incomprehensible rats nest if we are not strict about style and organization. Here is the general structure of the Python programs we will write:
类似地,大多数烹饪书提供了许多其他食谱所使用的基本食谱,例如制作调味汁。烹饪书被组织成一系列可执行的食谱,其中一些“调用”其他食谱。 为了做晚餐,我打开一本食谱,获取一些原料,然后按照特定的顺序执行一个或多个食谱。
*import any libraries*<br>
*define any constants, simple data values*<br>
*define any functions*<br>
*main program body*
编写程序的方式也是一样的。打开烹饪书与导入库相同。获取原材料可能意味着将数据加载到内存中。主程序调用函数(食谱)来完成特定任务。作为编写程序的一部分,我们通常会将代码的逻辑部分分解为特定于我们问题的函数,而库中的函数则倾向于广泛适用。
## Functions are subprograms
我们组织代码的方式很重要。 如果我们对风格和组织不严格,程序很快就会成为难以理解的老鼠窝。 以下是我们将编写的 Python 程序的一般结构:
A sequence of operations grouped into a single, named entity is called a **function**. Functions are like mini programs or subprograms that we can plan out just like full programs.
Python **programs** consist of zero or more functions and the so-called "main" program, consisting of a sequence of operations that gets the ball rolling.
+ 导入任何库
+ 定义任何常量,简单的数据值
+ 定义任何函数
+ 主程序体
Instead of loading data from the disk, functions operate on data given to them from the invoking program. This incoming data is analogous to a recipe's list of ingredients and is specified in the form of one or more named *parameters* (also called *arguments*). Instead of printing a result or displaying a graph, as a program would, functions *return* values. Functions are meant as helper routines that are generically useful.
## 作为子程序的函数
We begin planning a function by identifying:
1. a descriptive function name
2. the kind of value(s) it operates on (parameter types)
3. the kind of value it returns (return type)
4. what the function does and the value it returns
分组为单个命名实体的一系列操作称为**函数**。函数就像迷你程序或子程序,我们可以像完整的程序一样规划。
Python **程序**由零个或多个函数和所谓的“主”程序组成,它由让事情开始的一系列操作组成。
If we can't specifying exactly what goes in and out of the function, there's no hope of determining the processing steps, let alone Python code, to implement that function.
函数不从磁盘加载数据,而是操作由调用程序提供给它们的数据。 这个输入数据类似于食谱的成分列表,并以一个或多个命名*形式参数*(或者称为*参数*)的形式指定。函数不像程序那样打印结果或显示图形,而是*返回*值。函数是指广泛有用的辅助例程。
我们通过确定以下内容开始规划函数:
1.描述性函数名称
2.它操作的值的类型(参数类型)
3.它返回的值的类型(返回类型)
4.函数做了什么和返回的值
As with a program's work plan, we then manually write out some sample function invocations to show what data goes in and what data comes out.
如果我们无法确切地指定函数的内部和外部,那么就没有希望确定处理步骤,更不用说实现该函数了的 Python 代码了。
Once we fully understand our goal, we plan out the sequence of operations needed by the function to compute the desired result. As when designing a whole program, we start with the return value and work our way backwards, identifying operations in reverse order. Note: The operations should be purely a function of the data passed to them as parameters---functions should be completely ignorant of any other data. (More on this when we actually translate function pseudocode to Python.)
与程序的工作计划一样,我们手动写出一些示例函数调用,来展示输入数据和输出数据。
## Function templates
一旦我们完全理解了我们的目标,我们就会规划出函数所需的操作顺序,来计算所需的结果。在设计整个程序时,我们从返回值开始,向后工作,以相反的顺序确定操作。注意:操作应该纯粹是数据的函数,数据作为参数传递给它们 -- 函数应该完全不知道任何其他数据。(当我们实际将函数伪代码转换为 Python 时,会有更多相关内容。)
Python functions are like black boxes that, in general, accept input data and yield (return) values. Each invocation of a function triggers the execution of the code associated with that function and returns a result value or values. For example, here is a function called `pi` that takes no parameters but returns value 3.14159 each time it is called:
## 函数模板
Python 函数就像黑盒子,通常接受输入数据和并`yield`(或返回)值。每次调用函数都会触发与执行该函数的关联代码,并返回一个或多个结果值。例如,这是一个名为`pi`的函数,它不带参数,但每次调用时返回值`3.14159`
```python
def pi():
return 3.14159
```
The code template for a function with no arguments is:
没有参数的函数的代码模板是:
```py
def funcname():
......@@ -55,10 +59,11 @@ def funcname():
return expression
```
with holes for the function name, statements associated with a function, and an expression describing the return value. Functions that have no return value skip the `return` statement.
带有函数名称,与函数关联的语句以及描述返回值的表达式的空位。 没有返回值的函数没有`return`语句。
<img src="img/redbang.png" width="30" align="left"> The way that we associate statements with a function in Python is by indentation. So `return 3.14159` is part of the function because it is indented after the function header. The first statement that begins in the same column as the `def` is first statement outside of the function.
<img src="img/redbang.png" width="30" align="left">
我们将语句与 Python 中的函数关联的方式是缩进。 所以`return 3.14159`是函数的一部分,因为它在函数头之后缩进。与`def`在同一列中的第一个语句是函数外的第一个语句。
```python
def pi():
......@@ -69,10 +74,11 @@ print("this is not part of function")
```
<img src="img/redbang.png" width="30" align="left">*The Python interpreter does not execute the code inside the function unless we directly invoke that function.* Python sees the function definition as just that: a "recipe" definition that we can call if we want.
<img src="img/redbang.png" width="30" align="left">
The *definition* of a function is different than invoking or *calling* a function. Calling a function requires the function name and any argument values. In this case, we don't have any arguments so we call the function as just `pi()`:
*除非我们直接调用该函数,否则 Python 解释器不会执行函数内部的代码。* Python 将函数定义视为:我们可以根据需要调用的“食谱”定义。
函数的*定义*与调用*函数不同。调用函数需要函数名和任何参数值。在这种情况下,我们没有任何参数,所以我们将函数调用为`pi()`
```python
pi()
......@@ -80,38 +86,23 @@ pi()
# 3.14159
```
```python
pi
# <function __main__.pi()>
```
我们不需要`print`语句,因为我们在笔记本中执行,而不是在 Python 程序中执行。 如果这是在常规 Python 程序中,我们需要一个`print`语句:`print(pi())`,但当然这也适用于此。
We don't need a print statement because we are executing inside a notebook, not a Python program. If this were in a regular Python program, we would need a print statement: `print(pi())`, but of course that also works here.
Every invocation of that function evaluates to the value 3.14159. The function `return`s a value but `print`s nothing. For example, Jupyter notebooks or the Python interactive shell does not print anything if we assign the result to variable:
每次调用该函数的结果都是`3.14159`。 函数返回一个值但是不打印任何东西。 例如,如果我们将结果赋给变量,则 Jupyter 笔记本或 Python 交互式 shell 不会打印任何内容:
```python
x = pi()
```
We distinguish between functions and variables syntactically by always putting the parentheses next to the function name. I.e., `pi` is a variable reference but `pi()` is a function call.
Some functions don't have return values, such as a function that displays an image in a window. It has a *side effect* of altering the display but does not really have a return value. The `return` statement is omitted if the function does not return a value. Here's a contrived side-effecting example that does not need to return a value:
我们总是将括号放在函数名旁边,从语法上区分函数和变量。即,`pi`是一个变量引用,但`pi()`是一个函数调用。
某些函数没有返回值,例如在窗口中显示图像的函数。它有改变显示的*副作用*但实际上没有返回值。如果函数没有返回值,则省略`return`语句。这是一个人为的副作用示例,不需要返回值:
```python
def hi():
......@@ -123,8 +114,7 @@ hi()
```
If you try to use the value of a function that lacks a `return`, Python gives you the so-called `None` value.
如果你试图使用缺少`return`的函数的值,Python 会给你所谓的`None`值。
```python
x = hi()
......@@ -136,9 +126,7 @@ None
'''
```
Naturally, we can also return strings, not just numbers. For example here's a function called `hello` that does nothing but return string `'hello'`:
当然,我们也可以返回字符串,而不仅仅是数字。 例如,这是一个名为`hello`的函数,它只返回字符串`'hello'`
```python
def hello():
......@@ -157,26 +145,29 @@ print(id, phone)
# parrt 5707
```
现在转到更有趣的案例,这里是带有一个参数的函数的模板:
Turning to the more interesting cases now, here is the template for a function with one argument:
`def` *funcname*`(`*argname*`)`:<br>
&nbsp;&nbsp;&nbsp;&nbsp;*statement 1*<br>
&nbsp;&nbsp;&nbsp;&nbsp;*statement 2*<br>
&nbsp;&nbsp;&nbsp;&nbsp;*...*<br>
&nbsp;&nbsp;&nbsp;&nbsp;`return` *expression*<br>
```py
def funcname(argname):
statement 1
statement 2
...
return expression
```
If there are two arguments, the function header looks like:
如果有两个参数,则函数头如下所示:
`def` *funcname*`(`*argname1*, *argname2*`)`:<br>
```py
def funcname(argname1, argname2):
```
Our job as programmers is to pick a descriptive function name, argument name(s), and statements within the function as per our function workplan.
我们作为程序员的工作是,根据我们的函数工作计划,选择函数中的描述性函数名称,参数名称和语句。
**Invoking a function** with arguments looks like *funcname*`(`*expression*`)` or *funcname*`(`*expression1*`,` *expression2*`)` etc... The order of the arguments matters. Python matches the first expression with the first argument name given in the function definition.
**调用带参数的函数**看起来像`funcname(expression)``funcname(expression1, expression2)`等等...参数的顺序很重要。Python 将第一个表达式匹配函数定义中给出的第一个参数名称。
Let's take a look at some of the code snippets from [Programming Patterns in Python](python-patterns.ipynb) and see if we can abstract some useful functions.
让我们看一下[ Python 中的编程模式](python-patterns.ipynb)中的一些代码片段,看看我们是否可以抽象一些有用的函数。
## Sum function
## 求和函数
In [Model of Computation](computation.ipynb), we saw code to translate mathematical Sigma notation to python and so this code to sum the values in a list should be pretty familiar to you:
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册