1.
Required Arguments
These are the arguments that must be passed to the function in the correct positional order.
def add(a, b):
return a + b
# Calling the function
result = add(5, 3) # Required arguments
print(result) # Output: 8
2. Keyword Arguments
With keyword arguments, you can specify arguments by their name instead of the order
def introduce(name, age):
print(f"My name is {name} and I am {age} years old.")
# Calling with keyword arguments
introduce(age=25, name="Alice") # Order does not matter here
3. Default Arguments
In default arguments, if a value for a parameter is not provided, the function uses a default value.
def greet(name, msg="Hello"):
print(f"{msg}, {name}!")
# Calling without the second argument uses the default value
greet("John") # Output: Hello, John!
# Calling with both arguments
greet("John", "Good Morning") # Output: Good Morning, John!
4. Variable-length Arguments
These allow you to pass a variable number of arguments to the function.
Arbitrary Positional Arguments (*args): Accepts a tuple of arguments.
def sum_all(*numbers):
total = 0
for num in numbers:
total += num
return total
# Passing variable number of arguments
result = sum_all(1, 2, 3, 4, 5)
print(result) # Output: 15
Arbitrary Keyword Arguments (**kwargs): Accepts a dictionary of keyword arguments.
def display_info(**info):
for key, value in info.items():
print(f"{key}: {value}")
# Passing keyword arguments
display_info(name="Alice", age=25, country="USA")
# Output:
# name: Alice
# age: 25
# country: USA
By default (*numbers) will accept inputs in tuple format and (**numbers) in dictionary format
If you want to accept your data into set and list you need to convert it.
For set
def add_to_set(*elements):
my_set = set(elements)
return my_set
# Passing variable number of arguments
result_set = add_to_set(1, 2, 3, 4, 5)
print(result_set) # Output: {1, 2, 3, 4, 5}
for list
def add_to_list(*elements):
my_list = list(elements)
return my_list
# Passing variable number of arguments
result_list = add_to_list(1, 2, 3, 4, 5)
print(result_list) # Output: [1, 2, 3, 4, 5]