*args and **kwargs

Sending an unlimited amount of args to a function

*args = arguments

**kwargs = keyword arguments

result = sum((1,2,3,4,5)) # Using a tuple
# prints 15

Defining your own function with unlimited args

args:

# Limited function
def my_sum(a,b,c,d):
	return(a+b+c+d) # Limited to amount of args
# Adding an extra arg will retun
# takes 4 positional args but 5 were given


# Unlimited function
def my_sum(*args):
	return sum(args) # Sums unlimited amount of numbers

kwargs:

def key_value_func(**kwargs): # Requires variable name and value
	print(kwargs)
	
# ALWAYS USES KEY VALUE PAIRS
key_value_function(name="mike", weight=200, age=27):
	print(kwargs.keys())        # This will print only the keys
	print(kwargs.values())      # This will print only the values
	print(kwargs.get("weight")) # This will get the value of the key
# Prints the key value pairs in a DICTIONARY

NOTE: None is a value in python which represents the idea of nothing

Last updated