October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober 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: Stop Repeating Yourself and Reuse Your Code

Python functions let you name an operation, reuse it with different arguments, and return values for the rest of your program to use.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A Python function gives a useful operation a name so you can define it once, call it with different inputs, and optionally get a result back. Use def to define one, pass arguments when you call it, and use return when later code needs its result.

Define a function, then call it

The Python Tutorial puts it simply: “The def keyword introduces a function definition.” The indented body runs when the function is called—not when Python first reads the definition. Defining the function makes its name available; calling it executes its behavior.

def make_greeting(name):
    """Return a greeting for one person."""
    return f"Hello, {name}!"

first = make_greeting("Ari")
second = make_greeting("Sam")

Here, make_greeting names the operation, and name is its parameter. The strings "Ari" and "Sam" are arguments: values supplied at the call. Each call returns a string, which the caller stores in a variable. It could also combine that value with other data or print it.

The docstring—the string immediately inside the function—describes its purpose. Documentation tools can use docstrings to generate or browse documentation, so a short, accurate description is useful when the function’s behavior is not obvious.

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

Choose how callers supply inputs

Python functions can accept inputs in different ways. Positional arguments are concise but depend on order; keyword arguments make the intended parameter explicit; defaults let callers omit an input when a sensible optional behavior exists.

Style Example When it helps
Positional make_greeting("Ari") Compact calls where the parameter order is clear.
Keyword make_greeting(name="Ari") More explicit calls, especially when a function accepts several inputs.
Default def make_greeting(name="there"): An input is genuinely optional and has an appropriate fallback.

For more constrained APIs, Python also supports positional-only and keyword-only parameter markers. They let a function author restrict how a parameter may be supplied; use them when that restriction makes the intended interface clearer, not merely to make a short function look sophisticated. See the Python Tutorial’s sections on defining functions.

Return a value when the caller needs it

return hands a value back to the code that called the function. That makes the result available for assignment, further calculation, or another function call.

def add_tax(price, rate):
    return price * (1 + rate)

total = add_tax(20, 0.1)
print(total)

Printing and returning are different. print() displays a value as a side effect; it does not hand that value back as the function’s result. A function that reaches its end without a return expression produces None. Writing return without an expression does the same.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
def show_greeting(name):
    print(f"Hello, {name}!")

result = show_greeting("Ari")
print(result)  # None

Choose printing when the function’s job is to display something. Choose returning when its caller should decide what to do with the result. A returned value can be reused; text printed inside a function has already gone to the output stream.

Use mutable defaults carefully

Python evaluates a default argument expression once, when the def statement runs—not afresh for each call. If that expression creates a mutable object such as a list or dictionary, mutations can persist across calls that omit the argument.

def add_item(item, items=[]):
    items.append(item)
    return items

print(add_item("a"))  # ["a"]
print(add_item("b"))  # ["a", "b"]

That behavior is often surprising when each call is meant to start with an empty list. Use None as the default and create a new list inside the function instead:

def add_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

print(add_item("a"))  # ["a"]
print(add_item("b"))  # ["b"]

When a caller supplies an existing list, this version appends to that list. When the caller omits it, the function creates a fresh one. The Python Programming FAQ explains why mutable default values can retain state between calls.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Decide what should become a function

Functions are useful when a meaningful operation appears in multiple places or deserves a clear name. They help keep behavior in one place and let callers provide different inputs. Not every repeated short line needs its own function: extraction is most helpful when the name makes intent clearer or when changing the behavior in one place matters.

  • Give the function a name that describes what it does.
  • Keep its purpose focused so callers can understand its input and output.
  • Return a value if later code needs to use it; print only when displaying output is the intended action.
  • Use defaults only for genuinely optional inputs, and avoid mutable objects as defaults when each call should get a fresh object.

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
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair 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.