# python函数用法详解

python中的函数定义比较简单，但是由于参数的形式多样就导致可以定义非常灵活的函数，下面主要总结下python中函数的知识点。

## 1.定义

```1 def funcName(args):
2 	funcBody
```

```1 def maxx(a, b):
2 	if a < b:
3 		return b
4 	else:
5 		return a
```

print(maxx(5, 3)) #输出5

## 2.参数的多种形式

##### 2.1默认参数

```1 def maxx(a, b = 10):
2 	if a > b:
3 		return a
4 	return b
5
6 print(maxx(5, 3))   #输出5
7 print(maxx(5))      #输出10
```
##### 2.2变长参数

```1 def fun(*args):
2 	for x in args:
3 		print(x)
4
5 fun(2, 3, 4, 5, 6)   #输出5个参数：2， 3， 4， 5， 6
```

##### 2.3关键字参数

```1 def print_info(**args):
2 	print(args)
3 	if 'age' in args:
4 		print(args['age'])
5 	if 'name' in args:
6 		print(args['name'])
7
8 print_info(name='aa', age=18)  #会输出{'age': 18, 'name': 'aa'} 18 aa
```

``` 1 def get_info(name, age, **args):
2     print('name = {0}, age = {1}'.format(name, age))
3     if 'sex' in args:
4         print('sex =', args['sex'])
5     if 'city' in args:
6         print('city =', args['city'])
7
8 get_info('zhangsan', 19)       #name = zhangsan, age = 19
9 get_info('zhangsan', 19, sex='M')   #name = zhangsan, age = 19 sex = M
10 get_info('zhangsan', 19, sex='M', city='hangzhou')   #name = zhangsan, age = 19 sex = M city = hangzhou
```
##### 2.4命名关键字参数

```1 def get_info(name, age, *, city):
2 	print('name = {0}, age = {1}, city = {2}'.format(name, age, city))
3 get_info('zhangsan', 19, city='hangzhou')
```