Sometimes, we need a function that can accept **any number of arguments**. Python allows this by using the *args syntax. ➤ *args allows you to pass multiple **positional arguments** as a tuple. ➤ It helps when the number of arguments is **not fixed**.
# Function to sum numbers
def add(*args):
s = 0
for x in args:
s += x
return s
# Function calls
result1 = add(10, 20, 30, 40)
result2 = add(1, 2, 3)
print(result1) # Output: 100
print(result2) # Output: 6
You can also use **required arguments** along with *args. This means the first argument is **mandatory**, and the rest are optional.
# Function with a required argument
def avg(first, *rest):
second = max(rest)
return (first + second) / 2
# Function call
result = avg(40, 30, 50, 25)
print(result) # Output: 45.0
Instead of positional arguments, you may need to pass **named arguments** (key-value pairs). ➤ **kwargs allows you to pass **any number of keyword arguments** as a dictionary. ➤ This is useful when you don’t know **how many named arguments** will be provided.
# Function with **kwargs
def addr(**kwargs):
for k, v in kwargs.items():
print(f"{k}: {v}")
# Function calls
addr(Name="John", City="Mumbai")
addr(Name="Raam", City="Mumbai", ph_no="9123134567", PIN="400001")
