第七章第3讲:python函数的关键字参数、默认参数、(收集参数)

时间:2019-07-21 13:17:22   收藏:0   阅读:121

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))

 

原文:https://www.cnblogs.com/ling07/p/11220867.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!