# python基础函数有哪些？python函数大全

XAMPP案例 48浏览

## 6 函数（一）

``In [1]: def add(x,y):``   ...:     z = x + y``   ...:     return(z)``

````In [2]: add(1,2)``Out[2]: 3````
````In [3]: add(20,30)``Out[3]: 50````

````In [4]: add(1,2,3)``---------------------------------------------------------------------------``TypeError                                 Traceback (most recent call last)``<ipython-input-4-ff1b6584ceb8> in <module>()``----> 1 add(1,2,3)````
````TypeError: add() takes 2 positional arguments but 3 were given````

### 6.1 参数

1. 位置参数

````In [5]: def divide1(a,b):``   ...:     return(a/b)````
``````
````In [6]: def divide1(b,a):``   ...:     return(a/b)````

````In [10]: divide1(1,2)``Out[10]: 0.5````
````In [11]: divide2(1,2)``Out[11]: 2.0````

1. 关键字参数

``In [12]: divide2(a=1,b=2)``Out[12]: 0.5``

``In [13]: divide2(b=2,a=1)``Out[13]: 0.5``

``In [14]: def divide3(a=1,b=1):``    ...:     return(a/b)``

``In [16]: divide3()``Out[16]: 1.0``

````In [17]: divide2()````---------------------------------------------------------------------------
``````TypeError
Traceback (most recent call last)
````<ipython-input-17-cca8e9725c78> in <module>()``----> 1 divide2()````
````TypeError: divide2() missing 2 required positional arguments: 'b' and 'a'````
1. 可变参数

````In [22]: def add2(*number):``    ...:     sum = 0``    ...:     for i in number:``    ...:         sum = sum + i``    ...:     return(sum)````
````In [23]: add2(1,2,3)``Out[23]: 6````
````In [24]: add2(1,2,3,4)``Out[24]: 10````

````In [25]: def add3(**number):``    ...:     sum = 0``    ...:     for i in number.values():``    ...:         sum = sum + i``    ...:     return(sum)``    ...:``    ...:````
````In [26]: add3(a=1,b=2,c=3)``Out[26]: 6````

Python把我们输入的关键字参数转化为字典，其中参数名称为字典的键，参数值为字典的值。我们再利用字典的相关操作，就可以得到结果了。

````In [27]: add2(a=1,b=2,c=3)``---------------------------------------------------------------------------``TypeError                                 Traceback (most recent call last)``<ipython-input-35-2bbba1f6b0dc> in <module>()``----> 1 add2(a=1,b=2,c=3)````
````TypeError: add2() got an unexpected keyword argument 'a'````
````In [28]: add3(1,2,3)``---------------------------------------------------------------------------``TypeError                                 Traceback (most recent call last)``<ipython-input-36-26389c411446> in <module>()``----> 1 add3(1,2,3)````
````TypeError: add3() takes 0 positional arguments but 3 were given````
1. 参数组合

``In [29]: def f1(a,b,c=1,*args,**kw):``    ...:     print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw)``

````In [30]: f1(1,2,3,4,5)``a = 1 b = 2 c = 3 args = (4, 5) kw = {}````
````In [31]: f1(1,2,3,4,e = 5)``a = 1 b = 2 c = 3 args = (4,) kw = {'e': 5}````
````In [32]: f1(1,2,3)``a = 1 b = 2 c = 3 args = () kw = {}````

## 6.2 返回多个值

````In [33]: def ff(a,b):``    ...:     return(a+b,a-b)````
````In [34]: ff(1,2)``Out[34]: (3, -1)````