args code example

Example 1: unlimited arguments python

def add(*args):		# *args takes multiple inputs
  return sum(args)


print(add(1,2,3,4,5))    # prints 15
print(add(10, 20, 30))	 # prints 60

Example 2: args kwargs python

>>> def argsKwargs(*args, **kwargs):
...     print(args)
...     print(kwargs)
... 
>>> argsKwargs('1', 1, 'slgotting.com', upvote='yes', is_true=True, test=1, sufficient_example=True)
('1', 1, 'slgotting.com')
{'upvote': 'yes', 'is_true': True, 'test': 1, 'sufficient_example': True}

Example 3: use of kwargs and args in python classes

def myFun(*args,**kwargs): 
    print("args: ", args) 
    print("kwargs: ", kwargs) 
    
myFun('my','name','is Maheep',firstname="Maheep",lastname="Chaudhary")

# *args - take the any number of argument as values from the user 
# **kwargs - take any number of arguments as key as keywords with 
# value associated with them

Example 4: **kwargs

When it iterating over a dictionary you are only able to iterate over 
the keys not the values. The ** when placed before a variable will allow
you to iterate and unpack both key and value pairs. Because you are 
unpacking both key and value this will return the result as a dictionary.

Example 5: python *args

# concatenate_keys.py
def concatenate(**kwargs):
    result = ""
    # Iterating over the keys of the Python kwargs dictionary
    for arg in kwargs:
        result += arg
    return result

print(concatenate(a="Real", b="Python", c="Is", d="Great", e="!"))

Tags: