第七章第3讲:python函数的关键字参数、默认参数、(收集参数)
1.关键字参数
作用:函数参数赋值时,不需要考虑函数代码块中参数的位置
def hello1(greeting,name): print("%s %s" % (greeting,name)) def hello2(name,greeting): # print("%s %s" % (name, greeting)) print("%s %s" % (greeting,name)) print(hello1("hello","world")) print(hello2("hello","world")) print(hello2(greeting="hello",name="world"))
2.默认参数
默认参数适用于在调用函数时未给函数传参的情况下。
def calculateTax(price=3,tax_rage=9): talTotal = price * tax_rage return talTotal print(calculateTax(6,2)) print(calculateTax()) 结果: 12 27
3.收集参数(*)
使用范围:不确定参数的个数时使用
# 收集参数 def many_params(*nums): #print(nums) return nums print(many_params("hello")) print(many_params(1,2,3)) def stdentInfo(name,*nums): # print(name,nums) return name,nums print(stdentInfo("Leo","Bella",12,"sex")) 结果: ('hello',) (1, 2, 3) ('Leo', ('Bella', 12, 'sex'))