Python Learning Series · @onlysamarrr · Day 21 / 30

Day 21: Function Arguments

Day 21 covers function arguments: default values, *args for extra positional arguments (collected as a tuple) and **kwargs for extra keyword arguments (collected as a dict). Never use a mutable default like bag=[], because it is shared across calls.

Phase: Intermediate · Reels: 101/450 – 105/450

Quick Answer

Day 21 covers function arguments: default values, *args for extra positional arguments (collected as a tuple) and **kwargs for extra keyword arguments (collected as a dict). Never use a mutable default like bag=[], because it is shared across calls.

What You Will Learn

Code

def greet(name, msg="Hello"):
    return f"{msg}, {name}"

def total(*args, **kwargs):
    print(args, kwargs)
    return sum(args)

print(greet("Arhan"))
print(greet("Arhan", "Hi"))
print(total(1, 2, 3, tax=5))

def add(item, bag=None):
    if bag is None:
        bag = []
    bag.append(item)
    return bag

print(add("a"))
print(add("b"))

Output

Hello, Arhan
Hi, Arhan
(1, 2, 3) {'tax': 5}
6
['a']
['b']

Code Explained, Line by Line

  1. msg = "Hello" is a default argument: it is used when no value is given.
  2. *args collects extra positional arguments into a tuple.
  3. **kwargs collects extra keyword arguments into a dict.
  4. The bag = None pattern is the safe way: create a fresh list inside the function.
  5. With bag = None, add("a") and add("b") return separate lists, not one shared list.
Common Mistake: Never write def f(x, bag=[]):. That list is created once and shared across every call. Use None as the default and create the list inside.

Real-Life Use

Logging, APIs and flexible utilities use *args and **kwargs to accept any number of arguments.

Practice Task: Write a function that returns the sum of any number of numbers, using *args.

Test Yourself — MCQs

Select (tick) an option, then tap Check answer to see instantly whether your answer is right or wrong, with an explanation. You can change your answer and check again.

Q1. What does *args collect?

Q2. What does **kwargs collect?

Q3. Why is def f(bag=[]) a trap?

Today's 5 Reels (from the 90-Day Plan Excel)

101/450ConceptDefault arguments
102/450Live demo*args aur **kwargs demo
103/450Common mistakeMutable default ki galti
104/450QuizQuiz: sum of any numbers
105/450Interview / real lifeInterview: *args kya hai
← Day 20Day 22 →