File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11# 定义函数
22
3+ 在 Python 中,定义函数使用 ` def ` 语句。一个函数主要由三部分构成:
4+
5+ - 函数名
6+ - 函数参数
7+ - 函数返回值
8+
9+ 让我们看一个简单的例子:
10+
11+ ``` python
12+ def hello (name ):
13+ return name
14+
15+ >> > r = hello(' ethan' )
16+ >> > r
17+ ' ethan'
18+ ```
19+
20+ 在上面,我们定义了一个函数。函数名是 ` hello ` ;函数有一个参数,参数名是 name;函数有一个返回值,name。
21+
22+ 我们也可以定义一个没有参数和返回值的函数:
23+
24+ ``` python
25+ def greet (): # 没有参数
26+ print ' hello world' # 没有 return,会自动 return None
27+
28+ >> > r = greet()
29+ hello world
30+ >> > r == None
31+ ```
32+
33+ 这里,函数 ` greet ` 没有参数,它也没有返回值(或者说是 None)。
34+
35+ 我们还可以定义返回多个值的函数:
36+
37+ ``` python
38+ >> > def add_one (x , y , z ):
39+ ... return x+ 1 , y+ 1 , z+ 1 # 有 3 个返回值
40+ ...
41+ >> >
42+ >> > result = add_one(1 , 5 , 9 )
43+ >> > result # result 实际上是一个 tuple
44+ (2 , 6 , 10 )
45+ >> > type (result)
46+ < type ' tuple' >
47+ ```
48+
49+ # 小结
50+
51+ - 如果函数没有 ` return ` 语句,则自动 ` return None ` 。
52+
53+
You can’t perform that action at this time.
0 commit comments