# 定义函数

``````def my_abs(x):
if x >= 0:
return x
else:
return -x
``````

`return None`可以简写为`return`

### 空函数

``````def nop():
pass
``````

`pass`语句什么都不做，那有什么用？实际上`pass`可以用来作为占位符，比如现在还没想好怎么写函数的代码，就可以先放一个`pass`，让代码能运行起来。

`pass`还可以用在其他语句里，比如：

``````if age >= 18:
pass
``````

### 参数检查

``````>>> my_abs(1, 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: my_abs() takes exactly 1 argument (2 given)
``````

``````>>> my_abs('A')
'A'
>>> abs('A')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bad operand type for abs(): 'str'
``````

``````def my_abs(x):
if not isinstance(x, (int, float)):
if x >= 0:
return x
else:
return -x
``````

``````>>> my_abs('A')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in my_abs
``````

### 返回多个值

``````import math

def move(x, y, step, angle=0):
nx = x + step * math.cos(angle)
ny = y - step * math.sin(angle)
return nx, ny
``````

``````>>> x, y = move(100, 100, 60, math.pi / 6)
>>> print x, y
151.961524227 70.0
``````

``````>>> r = move(100, 100, 60, math.pi / 6)
>>> print r
(151.96152422706632, 70.0)
``````