Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

Unit 3 — Keyword Arguments & Default Arguments

Lesson 37 of 50 in the free Python Programming notes on Siksha Sarovar, written by Rohit Jangra.

Keyword Arguments and Default Arguments

Keyword Arguments

Arguments passed by explicitly naming the parameter — order does not matter.

def student_info(name, age, course):
    print(f"{name}, {age} years, {course}")

student_info(age=21, name="Riya", course="BCA")   # order doesn't matter

You can mix positional and keyword arguments, but positional must come first:

student_info("Amit", course="BTech", age=20)   # OK
# student_info(name="Amit", 20, "BTech")       # SyntaxError -- positional after keyword

Default Arguments

A parameter can have a default value, used when the caller does not supply that argument.

def greet(name, greeting="Hello"):
    print(f"{greeting}, {name}!")

greet("Riya")                 # Hello, Riya!  (uses default)
greet("Amit", "Good morning")  # Good morning, Amit! (overrides default)
greet("Zoya", greeting="Hi")    # Hi, Zoya! (keyword form)
Rule: default parameters must come after non-default parameters in the definition.
# def bad(a=1, b):     # SyntaxError -- non-default argument follows default
#     pass

def good(a, b=1):     # correct
    pass

Combining default + keyword args

def create_profile(name, age=18, city="Delhi"):
    print(f"{name}, {age}, {city}")

create_profile("Riya")                       # Riya, 18, Delhi
create_profile("Amit", 25)                     # Amit, 25, Delhi
create_profile("Zoya", city="Mumbai")            # Zoya, 18, Mumbai

args and *kwargs (bonus — variable-length arguments)

def total(*numbers):          # *args collects extra positional args into a tuple
    return sum(numbers)

print(total(1, 2, 3, 4))   # 10

def show_info(**details):      # **kwargs collects extra keyword args into a dict
    for key, value in details.items():
        print(key, ":", value)

show_info(name="Riya", age=21)

Mutable default argument pitfall

# DANGEROUS -- default list is created ONCE and shared across calls
def add_item(item, cart=[]):
    cart.append(item)
    return cart

print(add_item("book"))    # ['book']
print(add_item("pen"))     # ['book', 'pen']  -- unexpected! cart was reused

# SAFE version
def add_item_safe(item, cart=None):
    if cart is None:
        cart = []
    cart.append(item)
    return cart