1.函数的定义与调用
- 格式
def 函数名(形参...):
函数体
- 定义与调用
def add(a, b):
return a+b
print(add(10,20))
输出结果为:
30
- Python中return可以返回多个返回值
def add(a, b):
return a+b, 100
m,n=add(10,20)
print(m,n)
输出结果为:
30 100
2.函数参数
(1)必须参数(位置参数)
- 概念:按照顺序依次传参的参数
def add(a, b): #a,b为必须参数(位置参数)
return a+b
print(add(10,20))
30
(2)默认参数
- 概念:当调用的时候不用传值而使用默认值的参数
def add(a, b=20): #b为默认参数
return a+b
print(add(10))
30
(3)关键字参数
- 概念:指定对应参数的名字传参的参数
def add(a=1, b=2, c=3, d=4):
print(a, b, c, d)
add(d=100) #d为关键字参数
1 2 3 100
(4)不定长参数
- *args
- 概念: *args对应元组,可以接受多个参数
def add(*args): #*args为不定长参数
print(type(args), args, args[0])
add(10,11)
add(10,11,12,14)
<class 'tuple'> (10, 11) 10
<class 'tuple'> (10, 11, 12, 14) 10
- **kwargs
- 概念: **kwargs对应字典,可以将参数收集到一个字典中,参数的名字是字典的键,对应参数的值是字典的值
def add(**kwargs): #**kwargs为不定长参数
print(type(kwargs), kwargs)
add(x=10,y=11)
add(a=10,b=11,c=12,d=14)
<class 'dict'> {'x': 10, 'y': 11}
<class 'dict'> {'a': 10, 'b': 11, 'c': 12, 'd': 14}
3.匿名函数
- 概念:是指一个没有名称的函数。在 Python 中,普通函数使用 def 关键字定义,而匿名函数则使用 lambda 关键字定义。
- 格式:lambda (形参…):表达式
f=lambda x,y:x+y
print(f(10,20))
输出结果为:
30
4.递归函数
- 概念:直接或间接的调用自身的函数,称为递归函数。
- 注意:要有边界条件(结束条件)
#求阶乘
def f(n):
if n==1:
return 1
return n*f(n-1)
print(f(5))
输出结果为:
120