码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2019-07-21 13:40:12      阅读:88      评论:0      收藏:0      [点我收藏+]

标签:pre   范围   函数传参   使用   收集   tde   %s   代码   赋值   

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

 

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

标签:pre   范围   函数传参   使用   收集   tde   %s   代码   赋值   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!