1.必需参数
必需参数以正确的顺序传入参数,调用时的数量必需和声明时一样
1 def print_info (name,age): 2 print("My Name is :%s"%name) 3 print("Age:%d"%age) 4 5 print_info("qinyanli",27)
2.关键字参数
参数不需要按照顺序传入参数,调用函数时带上形参的关键字
1 def print_info (name,age): 2 print("My Name is :%s"%name) 3 print("Age:%d"%age) 4 5 print_info(age =27,name = "qinyanli")
3.默认参数
直接给形参赋默认值,如果需要修改默认值再改变。例如:Sex
1 def print_info (name,age,sex="male"): 2 print("My Name is :%s"%name) 3 print("Age:%d"%age) 4 print("Sex: %s"%sex) 5 6 print_info(age =27,name = "qinyanli")
4.不定长参数
a.声明时无命名参数
1 def add(*args): 2 sum = 0 3 print(args) 4 for i in args: 5 sum += i 6 print(sum) 7 add(1,2,3)
b.有命名参数
1 def print_info1(*args,**kwargs): 2 print(args) 3 print(kwargs) 4 5 print_info1('alex',18,'male',job = 'IT',hobby = 'girls')
打印结果:
1 ('alex', 18, 'male') 2 {'job': 'IT', 'hobby': 'girls'}
*args放在左边,**kwargs放在右边