Python Functions — def, Default Arguments, and Functions as Values
A function turns a block of code into a name you can call with different inputs. Define it once with def, give the common arguments defaults so short calls stay short, and pass functions themselves as values when the caller should decide what happens next. This guide builds each idea in small programs: an add function with a default, a greet function called with and without its argument, keyword arguments in any order, *args and **kwargs collecting what a caller sends, a lambda passed into another function, and the one trap that catches nearly every beginner, a mutable default argument shared by every call.
Written November 12, 2026 · Tested with Python 3.12.3 · 10 min read
- The main program: def, a default, and a function as a value
- def and return: a function without return gives back None
- Default arguments: the caller may leave it out
- Keyword arguments: name the values at the call
Written November 12, 2026
Tested with Python 3.12.3
What this guide is
A function is a named block that takes inputs, called arguments, and can hand one value back to the caller. Python defines a function with the keyword def, calls it by writing its name followed by parentheses, and returns a value with return. Three habits make functions pull their weight. Give an argument a default when most calls want the same value, and short calls get shorter. Let callers name their arguments, and a call with several values stays readable. Treat functions as values, and one function can accept another as an input, which is how small programs stay flexible without growing a class for every variation. This guide takes those ideas in order, then closes with the trap that follows from how Python builds default values: a mutable default is built once and shared by every call.
The main program: def, a default, and a function as a value
def add(a, b=10):
return a + b
def greet(name="world"):
return f"hello {name}"
def apply(f, x):
return f(x)
print("add(1,2)=", add(1, 2))
print("add(1)=", add(1))
print(greet())
print(greet("veldica"))
print("apply double=", apply(lambda v: v * 2, 21))
The exact output:
add(1,2)= 3
add(1)= 11
hello world
hello veldica
apply double= 42
Each line isolates one idea. add(1, 2) passes both arguments, so the function adds the values it was given. add(1) passes one argument, so b falls back to its default of 10 and the result is 11. greet() passes nothing at all, so name falls back to "world". greet("veldica") overrides the default. The last line passes a function into a function: apply receives a short anonymous function built with lambda, calls it on 21, and returns 42. The sections below take each part in turn.
def and return: a function without return gives back None
The line def add(a, b=10): opens the definition. The names inside the parentheses are the parameters, the indented block under the line is the body, and the body runs only when the function is called, not when it is defined. A call passes arguments in the order the parameters are declared, unless the call names them, which the keyword section below covers.
The return statement ends the call and hands a value back. A function with no return, or with a bare return, hands back the special value None. That is not an error, and it is the right shape for a function whose job is an effect, such as printing, rather than a value:
def shout(word):
print(word.upper())
result = shout("hello")
print("result is", result)
The exact output:
HELLO
result is None
The call printed HELLO as its effect, and the name result holds None because shout never returned anything else. Reading None where a real value was expected is a common first bug, and the usual cause is a missing return on one path through the function. When a function computes a value, every path that reaches the end with an answer needs its own return, or the caller gets None on the paths that fall through.
Default arguments: the caller may leave it out
A parameter with a value after an equals sign in the definition has a default. b=10 in add means a caller who passes one argument still gets a complete call, with 10 standing in for the missing second argument. name="world" in greet does the same for a string. Defaults suit values that most calls share: a greeting for a general reader, a count of 10, a mode that rarely changes.
Two rules shape where defaults can go. A parameter with a default must come after every parameter without one, so def add(a, b=10) is valid and def add(a=10, b) is a syntax error. And the default is part of the definition, so changing a default changes every short call at once. That shared nature is harmless for numbers and strings, and it is exactly what makes the mutable default trap at the end of this guide bite.
Keyword arguments: name the values at the call
A caller can name an argument instead of relying on position. Naming frees the order and documents the call at the same time:
def add(a, b=10):
return a + b
print("positional=", add(1, 2))
print("keyword=", add(a=1, b=2))
print("reordered=", add(b=2, a=1))
print("mixed=", add(1, b=5))
The exact output:
positional= 3
keyword= 3
reordered= 3
mixed= 6
The first three calls pass the same two values three ways and get the same answer. The fourth call mixes the two styles: 1 fills a by position, and b=5 overrides the default by name. Positional arguments must come first in a call, and a parameter can receive a value only once, so add(1, a=2) is an error rather than a choice of two values for a. Keyword arguments earn their keep as a call grows: add(b=2, a=1) cannot be misread, while two bare numbers can be swapped by accident and still run.
args and *kwargs: accept what the caller sends
A fixed parameter list fits a function that knows its inputs. Two special forms handle the rest. A parameter written *args collects any extra positional arguments into a tuple. A parameter written **kwargs collects any extra keyword arguments into a dict:
def total(*args):
return sum(args)
def show(**kwargs):
for key in sorted(kwargs):
print(f"{key}={kwargs[key]}")
print("total()=", total())
print("total(1,2,3)=", total(1, 2, 3))
show(name="ana", role="dev")
The exact output:
total()= 0
total(1,2,3)= 6
name=ana
role=dev
total() receives an empty tuple, and sum of an empty tuple is 0. total(1, 2, 3) receives the tuple (1, 2, 3). show receives the dict {"name": "ana", "role": "dev"} and prints its keys in sorted order, which is why the output order is fixed even though the caller wrote the pairs in that same order by luck. Wrapper functions use these two forms most: a wrapper declares *args and **kwargs, passes both on to the function it wraps, and stays correct no matter what the wrapped function accepts. The names args and kwargs are a convention; the stars are what Python reads.
Functions as values: pass the behavior in
A function name is a value like any other, so a function can be stored in a variable, kept in a list, or passed as an argument. The main program used the third of those: apply(f, x) calls whatever function arrives as f. The caller in that program passed a lambda, a one-expression function with no name:
def apply(f, x):
return f(x)
print(apply(lambda v: v * 2, 21))
lambda v: v * 2 builds a function that takes v and returns v * 2. A lambda holds one expression and returns its value, with no return keyword and no statements. It suits a small rule that exists for one call site, such as a sort key or a doubling rule. Anything longer, anything with a branch, and anything worth a name belongs in a def, where it can be read, reused, and called by name in an error message. A named function passes the same way, by its name with no parentheses: a double function defined with def double(v): return v * 2 gives apply(double, 21) the same result as the lambda version, 42. Writing double(21) instead would pass the number 42 into apply as the function, and the call inside apply would fail, because a number cannot be called.
Trap: a mutable default is shared by every call
def statement runs, and the same object serves every call that relies on it. For a number or a string nothing can change that object, so the sharing stays invisible. For a list, the sharing is the bug:def push(item, box=[]):
box.append(item)
return box
print(push("a"))
print(push("b"))
print(push("c", []))
print(push("d"))
The exact output:
['a']
['a', 'b']
['c']
['a', 'b', 'd']
The second call did not start from an empty list. It appended to the same list the first call built, because box=[] created one list at definition time and both short calls used it. The third call passed its own fresh list, so it printed ['c'] alone, and the fourth call went back to the shared list, which still held the first two items. Code that expects each call to start fresh will pass a quick test and fail in real use, once earlier calls have left values behind.
The standard fix is a None default with a fresh list built inside the body:
def push(item, box=None):
if box is None:
box = []
box.append(item)
return box
print(push("a"))
print(push("b"))
The exact output:
['a']
['b']
Now each short call builds its own list, and the two calls no longer see each other. The same rule covers dict and set defaults: any default the body can change belongs behind a None check, never in the definition line.
Which form for which job
| Job | Form | Why |
|---|---|---|
| A block of code used more than once | def with named parameters |
One definition, called by name with different inputs |
| An effect with no answer, such as printing | A function with no return |
The call returns None, which signals there is no value to use |
| A value most calls share | A default argument, as in b=10 |
Short calls stay short, and one change updates every short call |
| A call with several values that could be swapped | Keyword arguments | Each value carries its parameter name at the call site |
| Any number of positional inputs | *args |
The extras arrive as one tuple the body can loop or sum |
| Any set of named inputs | **kwargs |
The extras arrive as one dict, the wrapper pattern |
| A one-expression rule for one call site | lambda |
The rule sits where it is used, with no name to invent |
| A fresh list or dict per call | A None default plus a build in the body |
Each call gets its own object, so calls cannot leak into each other |
Checklist
- Before copying a block of code to a second place, name it with
defand call it twice instead. - Before relying on a function's result, confirm every path through it ends in a
return, or the missing path hands the callerNone. - Before adding a parameter, decide its default: a value most calls share belongs in the definition, after every parameter that has no default.
- Before writing a call with three or more bare values, name the arguments whose order a reader could swap.
- Before reaching for
*argsor**kwargsin a new function, check whether a fixed parameter list states the inputs more clearly; the open forms fit wrappers and truly open inputs. - Before using a list, dict, or set as a default value, replace it with
Noneand build the object inside the body.
Related guides on this site
- Python Lists, Dicts, and Sets — The Three Collections You Use Every Day — the collections that
*args,**kwargs, and the mutable default trap are built from. - Go Slices and Maps — Append, Length, Capacity, and Lookup — the Go counterpart for passing and growing collections, where a function receives a slice header rather than the collection itself.
Sources
- Python Tutorial, Defining Functions —
def, calls, and the rule that a function with noreturnreturnsNone. - Python Tutorial, More on Defining Functions — default values, keyword arguments, and the warning that a mutable default accumulates across calls.
- Python Tutorial, Lambda Expressions — small anonymous functions and passing a function as an argument.
- Python Language Reference, Function definitions — the function definition statement, parameter defaults evaluated at definition time, and
*argsand**kwargs.
Keep Exploring
The full Python hub \u2014 language basics, the standard library, and data tools.
Every guide on the site in one list, grouped by topic.
Every browser-only checker and verifier on the site.
The C++, Python, Sysadmin, Rust, Go, and TypeScript hubs.