Python Mastery – From Basics to Brilliance / Functions

args and kwargs

✅ args in Python

  • args lets a function accept a variable number of positional arguments. These are collected into a tuple, making your function more flexible.

def total(*numbers):
    return sum(numbers)

print(total(10, 20, 30))  # Output: 60

🔍 Key Points:

  • Useful when the number of arguments isn’t fixed.

  • Internally stored as a tuple.

  • args is a convention—you can name it anything.

  • Must appear after regular parameters in the function definition.

✅ *kwargs in Python

  • *kwargs lets a function accept any number of keyword arguments. These are packed into a dictionary.

def display_info(**info):
    for key, value in info.items():
        print(f"{key} : {value}")

display_info(name="Bob", age=25)

🔍 Key Points:

  • Stores named arguments as a dictionary.

  • Allows dynamic handling of inputs with keys.

  • kwargs is the convention—you can rename it.

  • Must come after regular parameters and args.



🧠 Quick Summary

Feature

*args

**kwargs

Type

Tuple

Dictionary

Usage

Positional arguments

Keyword arguments

Access

Loop with for item in args

Loop with for k, v in kwargs.items()


💡 Real-Life Analogy

🛵 Ordering Food Online

  • args → Just dishes: "Pizza", "Burger", "Pasta"

  • *kwargs → Labeled preferences: spicy=True, extra_cheese=True