Quiz 2

Function Arguments — Positional, Keyword, Default, Variable

627 words
3 min read
Python Week 1: the first filter for runtime behavior
Visual companion
Python
Type and operator map

Python Week 1: the first filter for runtime behavior

View
Revision summary

What this note is really saying

Short form

# Function Arguments — Positional, Keyword, Default, Variable > **Why read this?** Python's function arguments are incredibly flexible. You can have optional parameters (defaults), pass arguments by name (keywords), accept any number of arguments (*args), and accept any number of keyword arguments (**kwargs).

Function Arguments — Positional, Keyword, Default, Variable

Why read this? Python's function arguments are incredibly flexible. You can have optional parameters (defaults), pass arguments by name (keywords), accept any number of arguments (*args), and accept any number of keyword arguments (**kwargs). Mastering this makes your functions more reusable and readable.

🎯 Learning Objectives

By the end of this topic, you will be able to:
  1. Use positional and keyword arguments correctly
  2. Set default parameter values
  3. Use *args for variable positional arguments
  4. Use **kwargs for variable keyword arguments
  5. Understand argument ordering rules

📋 Prerequisites


📖 Core Content

22.1 Positional Arguments

python
# runnable
def describe_person(name, age, city):
    print(f"{name} is {age} years old and lives in {city}.")
# Positional: order matters
describe_person("Alice", 25, "New York")
describe_person("Bob", 30, "Los Angeles")

22.2 Keyword Arguments

python
# runnable
# Keyword: order doesn't matter
describe_person(city="Chicago", age=28, name="Charlie")
describe_person(name="Diana", age=22, city="Boston")
# Mix positional and keyword (positional FIRST)
describe_person("Eve", 35, city="Seattle")

22.3 Default Parameters

python
# runnable
def greet(name, greeting="Hello", punctuation="!"):
    print(f"{greeting}, {name}{punctuation}")
greet("Alice")                    # Hello, Alice!
greet("Bob", "Hi")                # Hi, Bob!
greet("Charlie", "Hey", ".")      # Hey, Charlie.
greet("Diana", punctuation="?")    # Hello, Diana?

22.4 *args — Variable Positional Arguments

python
# runnable
def sum_all(*args):
    """Sum any number of arguments."""
    print(f"Arguments: {args}")
    return sum(args)
print(sum_all(1, 2))           # 3
print(sum_all(1, 2, 3, 4, 5))  # 15
def multiply(first, *others):
    """Multiply first by product of others."""
    result = first
    for n in others:
        result *= n
    return result
print(multiply(2, 3, 4))  # 24 (2 * 3 * 4)

22.5 **kwargs — Variable Keyword Arguments

python
# runnable
def print_info(**kwargs):
    """Print key=value pairs."""
    for key, value in kwargs.items():
        print(f"{key}: {value}")
print_info(name="Alice", age=25, city="NYC")
print()
print_info(product="Laptop", price=999.99, in_stock=True)

22.6 Argument Ordering Rules

The order MUST be:
  1. Positional (normal)
  2. Default parameters
  3. *args (variable positional)
  4. Keyword-only (after *args)
  5. **kwargs (variable keyword)
python
# runnable
def complex_func(a, b, c=10, *args, verbose=True, **kwargs):
    print(f"a={a}, b={b}, c={c}")
    print(f"args={args}")
    print(f"verbose={verbose}")
    print(f"kwargs={kwargs}")
complex_func(1, 2, 3, 4, 5, verbose=False, mode="test", debug=True)

22.7 Unpacking Arguments

python
# runnable
def add(a, b, c):
    return a + b + c
# Unpack list/tuple
nums = [10, 20, 30]
print(add(*nums))  # 60
# Unpack dict
params = {"a": 5, "b": 3, "c": 2}
print(add(**params))  # 10

⚠️ Common Pitfalls

Pitfall 1: Mutable Default Arguments

The mistake: def add_item(item, lst=[]): lst.append(item); return lst Why: The default list is created ONCE, shared across all calls. Fix: def add_item(item, lst=None): if lst is None: lst = []; lst.append(item); return lst

Pitfall 2: Order Mix-up

The mistake: Placing *args before positional parameters — wrong order. Fix: Follow the rule: positional → default → *args → keyword-only → **kwargs.

Pitfall 3: Forgetting * in *args

The mistake: def func(args): when you meant def func(*args): Result: It works but only accepts ONE argument. Fix: Add the *: def func(*args): for variable arguments.

📝 Practice Questions

Q1: What does this output?
python
def func(a, b, *args):
    print(a, b, args)
func(1, 2, 3, 4, 5)
Answer: 1 2 (3, 4, 5) — a=1, b=2, args=(3,4,5) Q2: Write a function that accepts any number of keyword arguments and prints them.
Answer:
python
def print_kwargs(**kwargs):
    for k, v in kwargs.items():
        print(f"{k} = {v}")
Q3-10: Additional argument questions.
(Following pattern.)

🔗 Cross-References

Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.