• Index

### 关于作者

#### 定义函数

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

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

`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`包里的`sin``cos`等函数。

``````>>> 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)
``````

### 练习

ax2 + bx + c = 0

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

import math

----
pass
----
# 测试:
print(quadratic(2, 3, 1)) # => (-0.5, -1.0)
print(quadratic(1, 3, -4)) # => (1.0, -4.0)
```

def_func.py