*Args and **Kwargs

What are *args and **kwargs?

Python’s *args and *kwargs are special parameters used in function definitions to allow for undefined number or arguments. *args captures any extra positional arguments passed into the function as a tuple while **kwargs captures any additional keyword arguments as a dictionary thus help in creating functions that can adapt to various inputs in short making functions reusable and versatile.

Why use *args and **kwargs?

By using *args and **kwargs functions can handle optional or unknown numbers of arguments which is useful in cases where the number of inputs is unpredictable. For example, when organizing an event in a barangay you might want to record a varying number of expenses. With *args and **kwargs the function can adjust to any number of input making it ideal for these dynamic cases.

How to use it?

To use *args and *kwargs, simply define a function and add it as function arguments.

Syntax:

def function_name(*args, **kwargs):
  # Code block

Example

A simple program to calculate the total expenses in a Filipino Family Gathering.

def total_expenses(event, *expenses, **additional_expenses):
  total = sum(expenses)
  print(f"Total initial expenses for {event}: Php {total}")
  
  for item, cost in additional_expenses.items():
    total += cost
    print (f"Added {item}: Php {cost}")
  print(f"Total expenses for {event}: Php {total}")
  
total_expenses("Binyag", 500, 1200, 800, food=5000, drinks=2000, decorations=1500)

"""
Expected Output:

Total initial expenses for Fiesta: Php 2500
Added food: Php: 5000
Added drinks: Php: 2000
Added decorations: Php 1500
Total expenses for Fiesta: Php 11000
"""

Scroll to Top