Parameters
# coding=utf-8# 函数的参数def power(x): return x * x;print power(5)
After modification
def power_1(x,n=2): #默认参数可以简化函数的调用 s=1 while n > 0: n = n-1 s = s * x return sprint power_1(2,3)
Default parameters
def enroll(name,gender,age=6,city="beijing"): print (‘name:‘, name) print (‘gender:‘, gender) print (‘age:‘, age) print (‘city:‘, city)enroll(‘bob‘,‘F‘)def add_end(L=[]): L.append(‘END‘) return Lprint add_end()print add_end()print add_end()# 可变参数,传入的参数个数是可变的# def calc(numbers):def calc(*numbers): #定义可变参数和定义一个list或tuple参数相比,仅仅在参数前面加了一个*号 sum1 = 0 for n in numbers: sum1 = sum1 + n*n return sum1print calc(1,2)print calc()# 在list或tuple前面加一个*号,把list或tuple的元素变成可变参数传进去nums = [1, 2, 3]print calc(*nums)
Keyword parameters
**extra means that all key-value of this dict are passed to the **kw parameter of the function with the keyword argument extra
def person(name, age, **kw): print(‘name:‘, name, ‘age:‘, age, ‘other:‘, kw)person(‘Micheal‘,20)extra = {‘city‘: ‘Beijing‘, ‘job‘: ‘Engineer‘}person(‘Jack‘, 24, **extra) print person
Named keyword parameters
Keyword argument, the caller of the function can pass in any unrestricted keyword argument. As to exactly what is passed in, it needs to be checked inside the function via KW.
def person1(name,age,**kw): if ‘city‘ in kw: pass if ‘job‘ in kw: pass print(‘name:‘,name,‘age:‘,age,‘other:‘,kw)
The caller can still pass in the Unrestricted keyword parameter:
print person1(‘Jack‘, 24, city=‘Beijing‘, addr=‘Chaoyang‘, zipcode=123456)
To restrict the name of the keyword argument, you can use the named keyword parameter
A special delimiter is required for a named keyword Argument , and The following argument is treated as a named keyword parameter
Parameters of Python Learning