← Back to libraryQuestion 193 of 468
🐍PythonBeginner

Functions, Default and Keyword Arguments

📌 Definition:

Python functions are defined with def and support positional, default, keyword, and variable arguments. Defaults and keyword args make helper/utility functions flexible and readable.

📖 Detailed Explanation:

def login(user, password, remember=False) gives remember a default so callers can omit it. Callers can pass by position login('a', 'b') or by keyword login(user='a', password='b'), which improves readability. Keyword-only arguments (after a *) force explicit naming. A crucial gotcha: default argument values are evaluated ONCE at definition time, so using a mutable default like def f(items=[]) shares the same list across calls — a classic bug. Use None as the default and create the list inside instead.

🔑 Key Points:
  • Positional, default, and keyword arguments
  • Keyword calls improve readability (func(timeout=30))
  • Defaults evaluated ONCE at def time — beware mutable defaults
  • Use None default + create inside for mutable args
🌍 Real-World Example:

A reusable API helper: def call(endpoint, method='GET', headers=None, timeout=30) lets tests specify only what varies, defaulting the common cases.

🎯 Scenario-Based Interview Question:

def add_step(step, steps=[]): steps.append(step); return steps accumulates across calls unexpectedly. Explain and fix.