当函数的参数不确定时,可以使用*args 和**kwargs,*args 没有key值,**kwargs有key值。
还是直接来代码吧,废话少说
__author__ = 'Elvis'
#coding=utf-8def powersum(power, *args):
'''''Return the sum of each argument raised
to specified power.'''
total=0
for i in args:
total+=pow(i,power)
return total
print 'powersum(2, 3, 4)==', powersum(2, 3, 4)
print 'powersum(2, 10)==', powersum(2, 10)
def findad(username, **args):
'''''find address by dictionary'''
print 'Hello: ', username
for name, address in args.items():
print 'Contact %s at %s' % (name, address)
findad('wcdj', gerry='gerry@byteofpython.info',wcdj='wcdj@126.com', yj='yj@gmail.com')
结果:
powersum(2, 3, 4)== 25
powersum(2, 10)== 100
Hello: wcdj
Contact gerry at gerry@byteofpython.info
Contact yj at yj@gmail.com
Contact wcdj at wcdj@126.com
其他
def fun_var_args_call(arg1, arg2, arg3):
print "arg1:", arg1
print "arg2:", arg2
print "arg3:",arg3
kwargs = {"arg3": 3, "arg2": "two"} # dictionary
fun_var_args_call(1, **kwargs)
结果:
- arg1: 1
- arg2:"two"
- arg3:3