## Example 1: Packing args into a tuple
# Notice: The '*' operator before args variable
def sum_nums(a, b, *args):
total = a + b
if args:
print(type(args))
# rest of the values are inside 'args'
print(args)
for n in args:
total += n
return total
# passing only two arguments, so 'args' stays empty
print(sum_nums(2, 3)) # 5
# passing more than two arguments, now all values after 3 go into 'args'
print(sum_nums(2, 3, 4, 4, 2, 1, 1, 4)) # <class 'tuple'> \
# (4, 4, 2, 1, 1, 4) \
# 21
## Example 2: Packing kwargs into a dictionary
# Notice: The '**' operator before kwargs variable
def sum_nums2(x, y, **kwargs):
total = x + y
if kwargs:
print(type(kwargs))
# rest of the values are inside kwargs
print(kwargs)
# total the values
for v in kwargs.values():
total += v
return total
# passing only 2 arguments, so 'kwargs' stays empty
print(sum_nums2(2, 3)) # 5
# passing more than 2 arguments, now all values after 3 go into 'kwargs'
# Notice: Arguments should have some unique name,
# as they'll be the keys in 'kwargs' dictionary
print(sum_nums2(2, 3, a=2, b=4, d=4, any_name=5, my_var=8)) # <class 'dict'> \
# {'a': 2, 'b': 4, 'd': 4, 'any_name': 5, 'my_var': 8} \
# 28
# try using both 'args' & 'kwargs' in a function, print and check their values
def my_fun1(a, b, c, d):
return a + b + c + d
my_list = [1, 2, 3, 4]
my_dict = {"a": 1, "d": 4, "b": 2, "c": 3}
## Example 1: Unpacking from a list/tuple (list here), notice the '*' operator
print(my_fun1(*my_list)) # 10
## Example 2: Unpacking from a dictionary, notice the '**' operator
# Note: the keys of 'my_dict' should match the parameters of 'my_fun1()'
print(my_fun1(**my_dict)) # 10
# same goes for built-in functions too, 'print()' function unpacks
# the list values
print(*my_list) # 1 2 3 4