# 定义函数

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

return None可以简写为return

http://michaelliao.gitcafe.io/video/py/def-myabs.mp4

http://michaelliao.gitcafe.io/video/py/import-abstest.mp4

import的用法在后续模块一节中会详细介绍。

## 空函数

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 1 positional argument but 2 were given

>>> my_abs('A')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in my_abs
TypeError: unorderable types: str() >= int()
>>> 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

import math语句表示导入math包，并允许后续代码引用math包里的sincos等函数。

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

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

## 练习

ax<sup>2</sup> + bx + c = 0

>>> import math
>>> math.sqrt(2)
1.4142135623730951
# -*- coding: utf-8 -*-

import math