1. Positional parameters: general parameters
2. Default parameters:
1 def power(x, n=2): 2 s = 1 3 while n > 0: 4 n = n - 1 5 s = s * x 6 return s
There is a default assignment in the parameter. When calling, power(5) is the square, if power(5, 3) is the cube
If there are multiple default parameters, the default parameters are used in the front of the call, and the default parameters are not used later, you need to write "parameter name = parameter value" in the calling statement, such as the following situation
1 def enroll(name, gender, age=6, city='Beijing'): 2 print('name:', name) 3 print('gender:', gender) 4 print('age:', age) 5 print('city:', city)
enroll('bob','M',7) without parameter name is okay, city uses the default parameter 'beijing', age is useless, enroll('sary','F','hangzhou') is wrong Yes, because 'hangzhou' is not age, but city, so you need to use it like this: enroll('sary','F',city='hangzhou'), so age=6, city='hangzhou'
3. Variable parameters
1 def calc(numbers) 2 sum = 0 3 for n in numbers: 4 sum = sum + n * n 5 return sum
If you use the above code, for a list or tuple input value, such as [1,2,3], you need to write this when calling: calc([1,2,3]) or calc((1, 2, 3) ), which is troublesome
So variable parameters need to add * before numbers
1 def calc(*numbers) 2 sum = 0 3 for n in numbers: 4 sum = sum + n * n 5 return sum
So it can be called like this: calc(1, 2, 3).
For the list of nums = [1, 2, 3], if the variable parameter above is used, it cannot be written as calc(nums), it needs to be written as calc(nums[0], nums[1], nums[2]) or calc(*nums)
4. Keyword Arguments
1 def person(name, age, **kw) 2 print('name: ’, name, 'age: ', age, 'other: ', kw)
**kw is a dict. After the call statement is person('jackson', 30, gender='M', city='beijing'), the result is name: jackson age:30 other:{'gender' : 'M' , 'city' : 'beijing'}
For a defined dict such as extra = {'gender' : 'M', 'city' : 'beijing'}, you can call it like this: person('jackson', 30, **extra)
5. Named keyword arguments
It doesn't feel useful