SPECIAL FUNCTION DEFINITION


Default argument

Default argument values in Python allow you to specify default values for parameters in a function definition. If the caller of the function does not provide a value for these parameters, the default values will be used instead. This is useful for making certain parameters optional.

def test(a=10,b=20):
  result = a+b
  return result

print(test()) # use default argument
print(test(100,200)) # 100 and 200 overrides default argument
print(test(-5)) # -5 get assigned to a

Keyword arguments

Keyword arguments in Python allow you to pass arguments to a function using the parameter name explicitly. This provides clarity and flexibility when calling functions, especially when dealing with functions that have many parameters or default values. Here's how you define a function with keyword arguments:

def display(a=10,b=20,c=30):
  print(f'a={a} b={b} c={c}')

display(c=100,b=20) # keyword arguments provide us flexiblity to pass arguments in any order

Output:

a=10 b=20 c=100

when the formal parameter of the function is of the form: **kwargs, then it packs the keyword argument as the dictionary. Here is an example:

# use of **kwargs: it packs the keyword argument as dictionary
def test(**kwargs):
  print(type(kwargs))
  print(kwargs.keys(),kwargs.values())

test(name="apple",price=20,category="fruits") # function call using keyword arguments

when the formal parameter of the function is of the form: *args, it packs the list of values as tuples. Here is an example:

# use of *args: it packs the list of values as a tuple
def check(*args):
  for i in args:
    print(i)

check(10,20,30,40)

Both *args and **kwargs, can be combined as:

# both *args and **kwargs can be combined as:
def check(*args,**kwargs):
  print('List: ')
  for i in args:
    print(i)
  print('Dictionary: ')
  for k,v in kwargs.items():
    print(k,v)

check('a','b','c',x=10,y=20,z=30)