目录
目标
上篇博客中,我们在定义函数时,使用了空的括号。这表示它不需要任何信息就能完成相应的功能。
实际上,我们还可以在括号内传入一些东西,使函数的功能变得更加灵活。而括号内传入的东西,就是我们今天将要学习的函数的参数。
为函数设置参数
如图,我们在定义函数和调用函数时,通过传入参数的方式,可以控制输出的结果的差异性。

代码示例
python
# 定义一个函数sayWelcome,传入参数discount
def sayWelcome(discount):
print("欢迎光临")
print(f"商品一律{discount}")
# 调用函数,并传入参数"7.8折"
sayWelcome("7.8折")

第2行,定义函数时,在括号内指定了一个变量discount。
第7行,调用函数时,传入了具体的值"7.8折"。
形参
形参是定义函数时,括号内指定的变量名。形参本质就是"变量名",用于接收具体的数据。

实参
实参是调用函数时,括号内设置的数据。实参本质就是"数据",调用函数时,会把这个数据传递给形参。

传递实参
当然,如果我们想要函数接收更多的数据时,还可以在定义函数时,设置多个形参。与之对应,调用函数时就需要多个实参来传递数据。而向函数传递实参的方式有很多,这里我们介绍两种:关键字实参和位置实参。

关键字实参
调用函数时,直接在括号内指名道姓地对形参进行赋值。我们把这种传递实参的方式,称为关键字实参。

第2行,定义函数时,依次传入形参store,discount。第7行,调用函数时,明确指出了各个实参对应的形参。
python
# 定义一个函数sayWelcome,依次传入形参store,discount
def sayWelcome(store,discount):
print(f"欢迎光临{store}")
print(f"商品一律{discount}")
# 调用函数
sayWelcome(store="水果铺",discount="7.8折")

逗号
一个逗号,用来分隔多个参数。

关键字实参
调用函数时,使用 形参=实参 的方式传递数据。这里的store="水果铺",表示将"水果铺"传递给形参store。

关键字实参的顺序
使用关键字参数时,因为我们已经明确地指出了各个实参对应的形参。所以,在函数调用时,关键字实参的顺序无关紧要,只要给形参赋值相同的实参,结果都是等效的。

位置实参
关键字实参的优点就是能指名道姓地给形参传递数据。但是每次调用函数时,都需要重新输入形参名,稍微有一点麻烦。那么,有没有什么更方便的调用方法呢?实际上,我们还可以使用位置实参的方式来传递数据。

第2行,定义函数时,依次传入形参store,discount。第7行,调用函数时,按照位置顺序依次将实参处的数据,传递给形参处的变量名。
python
# 定义一个函数sayWelcome,依次传入形参store,discount
def sayWelcome(store,discount):
print(f"欢迎光临{store}")
print(f"商品一律{discount}")
# 调用函数
sayWelcome("水果铺","7.8折")

位置实参
调用函数时,传入的实参为具体的数据。这里的"水果铺"和"7.8折"将按照位置顺序,依次传递给形参store和discount。

常见错误
缺少实参
使用位置实参时,实参和形参的个数不一致是比较常见的一个错误。因为,形参会按照位置顺序依次接收实参处的数据。所以,在调用函数时,缺少实参会导致程序报错。

位置实参的顺序
位置实参的顺序很重要,如果指定错误,结果可能会出乎意料。如图,第二次调用函数时,最后会输出:狗有一只小明。

默认值形参
使用关键字实参和位置实参来给形参传递数据时,都必须保证实参和形参的个数相同。实际上,有些形参不一定需要接收实参的数据,我们可以提前给它们设置一个默认的值。
举个例子,我们经常将圆周率的值近似为3.14。所以,我们可以在定义函数时,直接给参数pi设置了默认值3.14。

定义一个函数getArea,用于计算圆的面积并输出。第2行,定义函数时,给形参pi设置为了3.14第7行,调用函数getArea,只设置了实参数据为2。
python
# 定义一个函数getArea,依次传入形参radius和pi,并设置pi为3.14
def getArea(radius, pi=3.14):
area = pi * radius * radius
print(f"半径为{radius}的圆,面积约为{area}")
# 调用函数,设置实参为2
getArea(2)

默认值形参
定义函数时,已经被复赋值的形参,我们称之为默认值形参。

参数的优先级
调用函数时,如果给默认值形参提供了实参值,那么该形参将优先使用实参值。如图,形参**pi
**会优先使用接收的实参值3.14159,而非默认值3.14。

默认值形参的位置
注意,在定义函数时,定义形参的顺序是:先写非默认的形参,后写默认值形参。也就是说,默认值形参只能放在非默认值形参的后面,否则会出现报错。可以这么理解:调用函数时,程序不知道数据2到底是用于修改pi的默认值,还是传递给radius。

总结
