Tutorials Python Python Arguments & Parameters
Ch 25 / 58
Python Intermediate 12 min read Chapter 25 of 58

Python Arguments & Parameters

Understanding how Python passes data into functions is fundamental to writing flexible, reusable code. Python supports six types of function parameters: positional, keyword, default, *args (variable positional), **kwargs (variable keyword), and keyword-only arguments. This chapter covers every type with an anatomy diagram, order rules, common pitfalls (mutable defaults!), and real-world design patterns used in professional Python APIs.

What you'll learn in this chapter
Parameters vs arguments — key distinction
Positional and keyword arguments
Default parameter values and mutable default trap
*args — variable number of positional arguments
**kwargs — variable number of keyword arguments
Keyword-only, positional-only & parameter order rules
Advertisement

Parameters vs Arguments

These two terms are often used interchangeably, but they have a precise distinction: parameters are the names in the function definition — they are the variables that receive values. Arguments are the actual values passed when the function is called.

Simple rule to remember Parameters live in the function definition. Arguments live in the function call. "A function has parameters; you call it with arguments."
Function Signature — Parameter Types Anatomy
def greet(
name
positional
,
title="Mr"
default
,
*args
var-positional
,
verbose
keyword-only
,
**kwargs
var-keyword
):
Parameters must follow this order — deviating causes a SyntaxError
Positional
Matched by position (order matters)
Keyword
Matched by name (order independent)
Default
Has a fallback value if not supplied
*args
Any number of positional args → tuple
**kwargs
Any number of keyword args → dict
Keyword-only
Must be passed by name — after *

Positional Arguments

Positional arguments are matched to parameters by their order. The first argument goes to the first parameter, the second to the second, and so on. If you pass the wrong number, Python raises a TypeError.

Python — positional_args.py
def greet(first_name, last_name):
    print(f"Hello, {first_name} {last_name}!")

# Positional — order matters!
greet("Alice", "Smith")   # Hello, Alice Smith!
greet("Smith", "Alice")   # Hello, Smith Alice! ← wrong order

# Too few arguments → TypeError
# greet("Alice")  → TypeError: missing 1 positional argument

# Too many → TypeError
# greet("A","B","C")  → TypeError: takes 2 positional arguments but 3 were given

# Positional with numeric parameters
def power(base, exponent):
    return base ** exponent

print(power(2, 8))    # 256  — base=2, exponent=8
print(power(8, 2))    # 64   — base=8, exponent=2 (order matters!)

Keyword Arguments

Keyword arguments are passed with the parameter name explicitly: func(name="Alice"). They can be in any order, make the call self-documenting, and can be mixed with positional arguments (positional must come first).

Python — keyword_args.py
def create_profile(name, age, city):
    print(f"{name}, {age}, from {city}")

# Keyword arguments — ORDER independent
create_profile(name="Alice", age=25, city="Vadodara")
create_profile(city="Vadodara", name="Alice", age=25)   # same result

# Mixed: positional first, then keyword
create_profile("Alice", age=25, city="Vadodara")   # ✅ OK
# create_profile(name="Alice", 25, "Vadodara")  → SyntaxError!

# Why use keyword args?
# Without keywords — hard to read
connect("localhost", 5432, True, "mydb", False)

# With keywords — self-documenting!
connect(
    host="localhost",
    port=5432,
    ssl=True,
    database="mydb",
    debug=False
)
Advertisement
K2infocom Python Masterclass & Backend Development
Master Python, Django & Backend APIs with AI
Go from absolute beginner to building production-ready REST APIs, web applications, and ML pipelines. Real projects, live mentoring in Vadodara, and placement support included.
2,400+
Students Enrolled
4.9 ⭐
Google Rating
6 Months
Full Program
100%
Placement Support
Python 3 Django & DRF FastAPI PostgreSQL Machine Learning Docker & AWS Real Projects AI Tools

Default Parameter Values

A parameter can have a default value specified with = in the function definition. If the caller doesn't supply that argument, the default is used. Parameters with defaults must come after parameters without defaults.

Python — default_args.py
def greet(name, greeting="Hello", punctuation="!"):
    print(f"{greeting}, {name}{punctuation}")

greet("Alice")                  # Hello, Alice!       ← both defaults used
greet("Bob", "Hi")              # Hi, Bob!            ← one default
greet("Carol", "Hey", ".")     # Hey, Carol.         ← no defaults
greet("Dave", punctuation="?")  # Hello, Dave?        ← keyword override

# ❌ Non-default before default → SyntaxError
# def bad(x=1, y):  → SyntaxError

# ════════ MUTABLE DEFAULT TRAP ════════════════════════
# ❌ WRONG — mutable default shared across all calls!
def add_item_bad(item, lst=[]):
    lst.append(item)
    return lst

print(add_item_bad("a"))  # ['a']
print(add_item_bad("b"))  # ['a', 'b']  ← BUG! 'a' still there!

# ✅ CORRECT — use None as sentinel
def add_item_good(item, lst=None):
    if lst is None:
        lst = []          # fresh list every call
    lst.append(item)
    return lst

print(add_item_good("a"))  # ['a']
print(add_item_good("b"))  # ['b']  ← correct, independent!
The Mutable Default Trap — most common Python gotcha! Default values are evaluated once at function definition time, not at each call. Using a mutable default (list, dict, set) means all calls share the same object. Always use None as the default and create the mutable object inside the function body.

*args — Variable Positional Arguments

*args allows a function to accept any number of positional arguments. Inside the function, args is a tuple containing all extra positional arguments. The name args is convention — you can use any name after the *.

Python — args_star.py
# *args collects extra positional args into a tuple
def total(*numbers):
    print(type(numbers))        # <class 'tuple'>
    return sum(numbers)

print(total(1, 2, 3))         # 6
print(total(1, 2, 3, 4, 5))   # 15
print(total())               # 0  — zero args OK

# Mixing positional param + *args
def log(level, *messages):
    for msg in messages:
        print(f"[{level}] {msg}")

log("INFO", "Server started")
log("ERROR", "DB down", "retrying...", "failed")

# Unpacking an existing list/tuple into positional args
nums = [10, 20, 30]
print(total(*nums))         # 60 — * unpacks the list

# Forward args to another function
def wrapper(*args):
    print("Before call")
    result = total(*args)     # pass args through
    print("After call")
    return result

**kwargs — Variable Keyword Arguments

**kwargs allows a function to accept any number of keyword arguments. Inside the function, kwargs is a dict containing all extra keyword arguments. It's widely used in framework code and decorators.

Python — kwargs_double_star.py
# **kwargs collects extra keyword args into a dict
def profile(**info):
    print(type(info))              # <class 'dict'>
    for key, val in info.items():
        print(f"  {key}: {val}")

profile(name="Alice", age=25, city="Vadodara")
# name: Alice  age: 25  city: Vadodara

# Mixing params + **kwargs
def create_user(username, email, **extra):
    print(f"User: {username}, {email}")
    print(f"Extra: {extra}")

create_user("alice", "alice@ex.com", role="admin", active=True)

# Unpacking a dict into keyword args with **
config = {"host": "localhost", "port": 8080}
print("{host}:{port}".format(**config))   # localhost:8080

# Building flexible API functions with *args + **kwargs
def make_request(method, url, *headers, **options):
    print(f"{method} {url}")
    print(f"Headers: {headers}")
    print(f"Options: {options}")

make_request(
    "GET", "https://api.example.com/users",
    "Content-Type: application/json",
    timeout=30, verify_ssl=True
)

Parameter Order Rules & Keyword-Only Arguments

Python enforces a strict order for parameters. Violating it causes a SyntaxError. Parameters after *args or after a bare * are keyword-only — they must be passed by name, never positionally.

# Parameter type Example Notes
1 Positional (no default) name Required, matched by position
2 Positional with default title="Mr" Optional; must come after required positional
3 *args *extras Collects remaining positional → tuple
4 Keyword-only (no default) verbose Must pass by name; after * or *args
5 Keyword-only (with default) debug=False Optional keyword-only
6 **kwargs **options Collects remaining keyword args → dict
Python — parameter_order.py
# Full parameter order example
def full_example(pos1, pos2, def1="a", *args, kw_only, kw_def=True, **kwargs):
    print(f"pos1={pos1}, pos2={pos2}")
    print(f"def1={def1}, args={args}")
    print(f"kw_only={kw_only}, kw_def={kw_def}")
    print(f"kwargs={kwargs}")

full_example(1, 2, "b", 3, 4, kw_only="required", extra="hi")

# ── Keyword-only with bare * ─────────────────────────
# After *, NO positional args can follow — only keyword-only
def send_email(recipient, *, subject, body, html=False):
    print(f"To: {recipient}")
    print(f"Subject: {subject}  HTML:{html}")
    print(f"Body: {body}")

send_email("alice@ex.com", subject="Hello", body="Hi there")
# send_email("a@b.com","Hello","Body")  → TypeError!
# subject and body MUST be keyword args

# ── Positional-only (Python 3.8+) ────────────────────
# Parameters before / can ONLY be passed positionally
def divide(dividend, divisor, /):
    return dividend / divisor

print(divide(10, 2))         # 5.0  ✅
# divide(dividend=10, divisor=2)  → TypeError!

# ── All types together ───────────────────────────────
def everything(pos_only, /, normal, *, kw_only, **kwargs):
    print(pos_only, normal, kw_only, kwargs)

everything(1, 2, kw_only=3)
everything(1, normal=2, kw_only=3, extra="ok")
Combining *args and **kwargs — the universal forwarder def wrapper(*args, **kwargs) accepts any combination of arguments. Call another function with func(*args, **kwargs) to forward everything unchanged — the standard pattern for decorators, middleware, and proxy functions.

Practice Python Online — Free Compilers

Don't want to install anything yet? Practice all argument and parameter examples from this chapter directly in your browser with these free Python environments.

▶
Online Python 3 Compiler
Write, run and debug Python code in your browser. No installation required. Test every function argument example instantly.
Open Compiler
Replit
Full IDE online
Google Colab
Free GPU notebooks
JupyterLite
Notebooks in browser
Programiz
Beginner-friendly
Chapter Summary
  • Parameters are names in the function definition; arguments are values passed at the call site.
  • Positional arguments are matched by order. Keyword arguments are matched by name and can appear in any order.
  • Default values make parameters optional. Non-default params must come before default params. Never use mutable objects as defaults — use None as sentinel.
  • *args collects any number of extra positional arguments into a tuple.
  • **kwargs collects any number of extra keyword arguments into a dict.
  • Keyword-only parameters appear after *args or a bare * — they must be passed by name.
  • Positional-only parameters (Python 3.8+) appear before / — they cannot be passed by keyword.
  • Required parameter order: positional → default → *args → keyword-only → **kwargs.
  • def fn(*args, **kwargs) is the universal forwarder — used in decorators and proxy functions to pass all arguments unchanged.
⚡
Free Resource
Download our Python Arguments & Parameters Cheat Sheet
All parameter types, order rules, *args/**kwargs, mutable default trap & real-world patterns — one printable page.
Get Sheet
Advertisement
Quick Check — Test Your Understanding
Question & Answer
✓ Answer

A parameter is the variable name defined in the function signature — it exists in the function definition. An argument is the actual value passed when the function is called.

def greet(name):    # name is a PARAMETER
    print(name)

greet("Alice")       # "Alice" is an ARGUMENT
✓ Answer

Default values are evaluated once at function definition time, not at each call. If the default is a mutable object (list, dict, set), all calls share the same object — mutations from one call persist to the next.

# ❌ WRONG
def bad(lst=[]):
    lst.append(1)
    return lst
print(bad())  # [1]
print(bad())  # [1, 1] ← BUG!

# ✅ CORRECT — use None sentinel
def good(lst=None):
    if lst is None: lst = []
    lst.append(1)
    return lst
✓ Answer

*args collects all extra positional arguments into a tuple. It is always a tuple, even when no extra arguments are passed (empty tuple ()).

**kwargs collects all extra keyword arguments into a dict. It is always a dict, even when no extra keyword arguments are passed (empty dict {}).

def demo(*args, **kwargs):
    print(type(args))    # <class 'tuple'>
    print(type(kwargs))  # <class 'dict'>
✓ Answer

Keyword-only arguments are parameters that must be passed by name — they cannot be supplied positionally. You define them by placing them after *args or after a bare * (when you don't want any variable positional args).

def send(to, *, subject, body):   # bare * enforces keyword-only
    pass

send("a@b.com", subject="Hi", body="Hello")  # ✅
# send("a@b.com","Hi","Hello")  → TypeError
✓ Answer

Python enforces this strict order (left to right):

  1. Positional-only (before /, Python 3.8+)
  2. Regular positional (no default)
  3. Positional with default
  4. *args (variable positional)
  5. Keyword-only (no default)
  6. Keyword-only with default
  7. **kwargs (variable keyword)

Deviating from this order causes a SyntaxError.

MCQ 1 of 3
Inside a function, what type is *args?
MCQ 2 of 3
What happens when you use a mutable list as a default argument and call the function twice?
MCQ 3 of 3
Which parameter type must be passed by name and cannot be supplied positionally?

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel