#默认参数 def power(x, n = 2): ans = 1 while n > 0: ans *= x return ans print(power(3)) def calc(numbers): sum = 0 for n in numbers: sum += n*n return sum print(calc([1, 3, 4]))#调用的时候需要组装一个list或者tuple print(calc((1, 4, 5))) print(‘rain‘)
#可变参数 def calc(numbers): sum = 0 for n in numbers: sum = sum +n*n return sum nums = [1, 2, 4, 10] print(calc(nums)) print(‘-----------------‘) #可变参数 def calc(*numbers): sum = 0 for n in numbers: sum = sum +n*n return sum nums = [1, 2, 4, 10] print(calc(*nums)) #加一个*把list或者tuple当成可变参数传进去 print(calc(1,2,3))#也可以直接传进去多个参数, 本质上nums接收到的是一个tuple print(‘----------‘) #关键字参数 def person(name, age, **kw): print(‘name:‘,name,‘age:‘, age, ‘other‘, kw) person(‘Michael:‘, 30) person(‘rain‘, 21, city = ‘xian‘) person(‘rain‘, 21, city = ‘shanghhai‘,gender=‘M‘) #也可以先组装出一个dict,然后,把该dict转换为关键字参数传进去:
时间: 2024-11-12 07:28:16