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 desk3 min

Python Functions: Define a Task Once, Call It Wherever You Need

Python functions let you name a task, pass it inputs, and reuse its returned result. Learn def, parameters, arguments, scope, defaults, and return values.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A Python function gives a task a name so you can call its code when needed, pass it inputs, and use any result it returns. Define one with def; the function is reusable within your program, while sharing it with another program requires separate module and import organization.

Define and call a function

Use def, a function name, parentheses, and a colon. The indented statements beneath it form the function body. Defining a function creates a function object and binds it to that name; the body runs when you call the function.

As an Amazon Associate I earn from qualifying purchases.

def greet(name):
    return f"Hello, {name}!"

message = greet("Sam")
print(message)

Here, name is a parameter—the name in the definition—and "Sam" is an argument—the value supplied in the call. greet("Sam") returns a string, which the caller stores in message before displaying it. A function’s first statement may optionally be a string literal used as its documentation string, or docstring. See the Python Tutorial’s function definition guidance.

Free tools Windows power users keep installed

One-click scans. No signup required.

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

Return a result when the caller needs it

return hands a value back to the caller. That value can be stored, combined with other values, or passed to another function. By contrast, print() displays something; it does not provide that displayed text as the function’s result. A function that reaches its end without a return expression returns None.

def area(width, height):
    return width * height

room_area = area(4, 3)
print(f"Room area: {room_area}")

Use printing when displaying output is the function’s purpose. Return a value when other code should decide what to do with it. To provide multiple results, return a tuple, which the caller can unpack:

def dimensions():
    return 4, 3

width, height = dimensions()

For the distinction between returned results and output parameters, the Python Programming FAQ explains why returning values is the usual approach.

Understand what function scope means

A function call has its own local names. Parameters and names assigned inside the function are local by default, so assigning to a name inside a function does not ordinarily rebind a variable of the same name in the caller. Python resolves names through local, enclosing, global, and built-in scopes. global and nonlocal explicitly request rebinding in an outer scope; use them only when that behavior is intended.

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

Python’s argument model is often described as “passed by assignment”: the function receives a value that refers to an object. Rebinding a local parameter does not rebind the caller’s variable, but mutating a shared mutable object—such as a list—can be visible to the caller. This is why “passed by reference” on its own can be misleading. The Python FAQ discusses this distinction.

Choose arguments that make calls clear

Python supports positional and keyword arguments. Positional arguments are compact; keyword arguments identify which value is for which parameter. A function definition can also restrict parameters to positional-only or keyword-only use.

def describe(item, *, color):
    return f"{color} {item}"

description = describe("mug", color="blue")

The * makes color keyword-only, so its role is explicit in the call. Positional-only parameters, written before / in a definition, can be useful when an API should not expose a parameter name or when preserving compatibility matters. These are design choices, not performance guarantees; the Python Tutorial documents the syntax and conventions.

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

Use defaults carefully

A default makes an argument optional for callers. Python evaluates the default expression once, when it executes the function definition—not anew on every call. Immutable defaults such as a number or string are often straightforward. A mutable default, such as a list or dictionary, is the same object across calls, so changes can persist.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
def add_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

first = add_item("pen")
second = add_item("book")

In this example, each call without an items argument creates its own list. If the caller supplies a list, the function appends to that supplied object. The behavior follows from when the default is evaluated; it is not a special exception raised by Python. The Python Tutorial describes default arguments and this mutable-default pitfall.

Use named functions for behavior you may reuse

Functions are objects: you can assign one to another name, pass it to another function, or return it from a function. A named def is usually easier to read when the logic needs explanation or documentation. A lambda can suit a small, single expression, but it does not replace a clear named function when behavior grows. The Python glossary and function tutorial cover functions as objects and lambda expressions.

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.

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. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

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.