9.md 1.3 KB
Newer Older
W
wizardforcel 已提交
1
# 函数
W
init  
wizardforcel 已提交
2 3 4 5 6

> 原文: [https://pythonspot.com/functions/](https://pythonspot.com/functions/)

函数是可重用的代码,可以在程序中的任何位置调用。 函数提高了代码的可读性:使用函数而不是冗长的指令列表,使人们更容易理解代码。

W
wizardforcel 已提交
7
最重要的是,可以重复使用或修改函数,这也提高了可测试性和可扩展性。
W
init  
wizardforcel 已提交
8

W
wizardforcel 已提交
9
## 函数定义
W
init  
wizardforcel 已提交
10 11 12 13 14 15 16 17 18 19

We use this syntax to define as function:

```py
def function(parameters):
    instructions
    return value

```

W
wizardforcel 已提交
20
**def 关键字**告诉 Python 我们有一段可重用的代码(一个函数)。 一个程序可以具有许多函数。
W
init  
wizardforcel 已提交
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44

## 实际例子

We can call the function using function(parameters).

```py
#!/usr/bin/python

def f(x):
    return(x*x)

print(f(3))

```

输出:

```py
9

```

该函数具有一个参数 x。 返回值是函数返回的值。 并非所有函数都必须返回某些内容。

W
wizardforcel 已提交
45
## 参数
W
init  
wizardforcel 已提交
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69

 We can pass multiple variables:

```py
#!/usr/bin/python

def f(x,y):
    print('You called f(x,y) with the value x = ' + str(x) + ' and y = ' + str(y))
    print('x * y = ' + str(x*y))

f(3,2)

```

输出:

```py

You called f(x,y) with the value x = 3 and y = 2
x * y = 6

```

[下载 Python 练习](https://pythonspot.com/download-python-exercises/)