October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk5 min

A Pythonic Guide to Functions: Define, Call, and Design Them in Python

A practical guide to Python functions: understand parameters and arguments, return values, parameter kinds, safe defaults, variadic arguments, lambdas, and annotations.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A Python function packages work behind a name: define it with def, pass values through its parameters, and use return when the caller needs a result. The key to writing clear functions is choosing a signature that makes valid calls obvious—and avoiding defaults that accidentally preserve state between calls.

Define a function and understand what a call does

A function definition binds a name to a function object. Python runs the indented body when that function is called, not when it reads the body during the definition. A function object can also be assigned to another name or passed to code that accepts a function.

def area(width, height):
    """Return the area of a rectangle."""
    return width * height

result = area(4, 3)

The first string literal in a function body is its docstring. It documents the function and is available to documentation tools and interactive browsing. A short, useful description is preferable to leaving callers to infer what the function does.

Parameters are the names written in the definition, such as width and height. Arguments are the values supplied in a call, such as 4 and 3. When called, the function receives its arguments under local names for that call.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A function that reaches the end without an explicit return value returns None. Printing and returning are different interfaces: print(value) displays something, while return value gives the result back to the caller so it can be stored, passed elsewhere, or used in another calculation.

Choose parameter kinds to make calls clear

Python lets a function control whether callers provide a parameter by position, by name, or only by name. The slash (/) and standalone asterisk (*) mark those boundaries.

def describe(item_id, /, format, *, include_details=False):
    ...

describe("A17", "short", include_details=True)  # valid
describe(item_id="A17", format="short")       # invalid: item_id is positional-only
describe("A17", format="short", True)          # invalid: include_details is keyword-only
  • Positional-only: Parameters before / must be supplied by position. The Python tutorial recommends this when a parameter name should not be part of the caller-facing interface; it can also make later parameter renaming less likely to break callers.
  • Positional-or-keyword: Parameters between / and * can be supplied either way. This is the usual behavior when neither marker is used.
  • Keyword-only: Parameters after a standalone * must be supplied by name. This is useful when a name explains the value or when accepting it by position would be unclear.

Keyword arguments can appear in different orders, but each parameter can receive a value only once. Required parameters still need values, and an unrecognized keyword is an error unless the function accepts extra keywords. Prefer names when they make a call easier to read, especially when several values have the same type or could be confused.

For a compact comparison: keyword-only parameters emphasize caller clarity; positional-only parameters keep parameter names out of the public call interface; positional-or-keyword parameters allow both styles. Choose the narrowest convention that fits the function’s intended use rather than allowing every possible form by default.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use defaults without accidentally sharing mutable state

A default expression is evaluated when Python executes the function definition, not each time the function is called. If the default is a mutable object and the function changes it, later calls can observe that same object.

def add_tag(tag, tags=[]):
    tags.append(tag)
    return tags

Here, calls that omit tags reuse the list created for the definition. If each call should start with a fresh list, use None as the default and create the list inside the function:

def add_tag(tag, tags=None):
    if tags is None:
        tags = []
    tags.append(tag)
    return tags

This pattern avoids unintended reuse while still allowing a caller to pass an existing list deliberately. A mutable default is not inherently wrong if shared, persistent state is the intended behavior; the hazard is treating a definition-time object as though it were freshly created for every call.

Use *args and **kwargs deliberately

In a function definition, *args collects extra positional arguments into a tuple, while **kwargs collects extra keyword arguments into a mapping. The Python tutorial describes arbitrary argument lists as the least frequently used option, so use them when flexibility is part of the function’s purpose—not as a substitute for a clear signature.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
def log_event(event, *details, **metadata):
    ...

log_event("connected", "worker-2", retry=1)

The same symbols can unpack values at a call site instead of collecting them in a definition:

coordinates = (10, 20)
options = {"format": "short"}

plot_point(*coordinates)
render_report(**options)

Use unpacking when you already have an iterable of positional values or a mapping of named values. Use variadic parameters when a function intentionally accepts a variable number of inputs, such as a wrapper forwarding arguments. Otherwise, explicit parameters tell callers which inputs the function supports and make mistakes easier to catch.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Use lambdas for small expressions, not full functions

A lambda creates an anonymous function whose body is limited to one expression. It is handy when a small function object is needed locally, for example as a sorting key:

items = [("pear", 3), ("apple", 1)]
sorted_items = sorted(items, key=lambda item: item[1])

For logic that needs multiple statements, a meaningful reusable name, or a docstring, write a normal def. A lambda is another way to express a function, not a general replacement for a named definition.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Add annotations as documentation, not runtime checks

Function annotations are optional metadata attached to a function. They can communicate expected input and output types to readers and tools, but Python does not automatically enforce those types during ordinary calls.

def area(width: float, height: float) -> float:
    """Return the area of a rectangle."""
    return width * height

The annotations describe an expectation; they do not prevent a caller from passing values of other types. Use them to make an interface easier to understand, and rely on appropriate validation or tools when enforcement is needed.

A practical checklist for function design

  • Give the function a name that says what it does, and add a docstring when it will help someone use or maintain it.
  • Make the function return a value when callers need to work with a result; do not confuse displaying output with returning it.
  • Use positional-only parameters when parameter names should not be part of the calling interface, and keyword-only parameters when names make calls clearer.
  • For a mutable value that should be new on each call, use a None default and initialize inside the function.
  • Prefer explicit parameters unless accepting or forwarding an open-ended set of arguments is a deliberate part of the design.
  • Use lambdas for small single expressions and annotations to document expectations, not to impose runtime type rules.

The Python Software Foundation’s Python 3.14.7 tutorial, “More Control Flow Tools”, documents these function behaviors and parameter conventions.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
  2. Cupertino desk5 min
    Apple Unveils AirPods Max 2: The Upgrade That Should Have Happened Years AgoAirPods Max 2 adds H2-powered audio features and Apple claims up to 1.5× more effective ANC, but its design, Smart Case, and 20-hour battery rating are unchanged. Wired lossless audio…
  3. Cupertino desk4 min
    Apple’s OLED Touch MacBooks Are Coming—but the Dynamic Island Is the Real GambleApple has not announced an OLED touchscreen MacBook, but reports point to high-end models arriving in late 2026 or early 2027. The reported Mac Dynamic Island could be useful, but…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.