*args is used when we want to send an arbitrary number of non-keyworded inputs to the function. The inputs are packed into a tuple inside the function.
**kwargs is used when we want to send an arbitrary number of keyworded inputs to a function. The inputs are packed into a dictionary inside the function.
They can be used in one function at the same time as well.
. The main functionality is driven by the asterisk * ; args and kwargs are just names. They are used by convention.
. Function input definition order should be
Arbitrary Number of Arguments : 訂定一個function 可以給定 “ 位意” 數量 input / arguement
def sum(*args):
print(args)
print(type(args)) # print args type
sum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
------------------------------------------
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
<class 'tuple'>
def sum(*args):
# sum 加法如何計算
result = 0
for number in range(0, len(args)):
print(f"we are now at number {number}")
print(f"also args[number] is {args[number]}")
result += args[number]
print(f"now the result is {result}")
return result
sum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
---------------------------------------
we are now at number 0
also args[number] is 1
now the result is 1
we are now at number 1
also args[number] is 2
now the result is 3
we are now at number 2
also args[number] is 3
now the result is 6
we are now at number 3
also args[number] is 4
now the result is 10
we are now at number 4
also args[number] is 5
now the result is 15
we are now at number 5
also args[number] is 6
now the result is 21
we are now at number 6
also args[number] is 7
now the result is 28
we are now at number 7
also args[number] is 8
now the result is 36
we are now at number 8
also args[number] is 9
now the result is 45
we are now at number 9
also args[number] is 10
now the result is 55
# **kwargs
def myfunc(**kwargs):
print(kwargs)
print(type(kwargs))
print(" {} now live in {} city" .format(kwargs["name"], kwargs["city"]))
myfunc(name="albert", gender="male", city="Taoyuan")
---------------------------
{'name': 'albert', 'gender': 'male', 'city': 'Taoyuan'}
<class 'dict'>
albert now live in Taoyuan city