iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more
A Python function lets you define a task once and call it wherever you need it in a program. Use def to create the function, give it parameters for input, and use return when callers need a result they can work with.
How to define and call a Python function
A function definition starts with def, a name, parentheses for parameters, and a colon. Its indented body runs when you call the function by name.
def greet(name):
return f"Hello, {name}!"
message = greet("Sam")
print(message)
Here, name is a parameter: a name in the function definition. "Sam" is an argument: the value supplied by the caller. The function returns a string, which the caller stores in message and then displays.
A docstring is an optional first statement in a function body, written as a string literal. It documents what the function does:
#1 Best Overall
def greet(name):
"""Return a greeting for one person."""
return f"Hello, {name}!"
The Python Tutorial, section 4.8, says: “The first statement of the function body can optionally be a string literal; this string literal is the function’s documentation string, or docstring.”
How functions make code reusable
Call a function each time you need its behavior instead of repeating the implementation. For example, a script can use one calculation in several places:
def area_of_rectangle(width, height):
return width * height
label_area = area_of_rectangle(4, 3)
box_area = area_of_rectangle(width=8, height=5)
combined_area = label_area + box_area
The function’s returned value can be assigned, combined with another value, or passed to another function. Defining a function makes behavior reusable within the program; sharing it with separate programs involves organizing code into modules and importing it.
Free tools Windows power users keep installed
One-click scans. No signup required.
Rank #2
Return a result or print it?
Use return when the caller should receive a value for later use. Use print() when the function’s purpose is to display something. Printing does not return the displayed text to the caller.
| Choice | Use it when | What the caller gets |
|---|---|---|
return value |
The result should be stored, combined, or passed onward. | The returned value; the function can also be used in an expression. |
print(value) |
The function should display output as a side effect. | No displayed value is returned automatically. |
If a function reaches its end without a return expression, it returns None. To return multiple results, return a tuple, which callers can unpack:
def min_and_max(values):
return min(values), max(values)
smallest, largest = min_and_max([4, 1, 9])
How function scope works
Each function call has its own local names. A name assigned inside a function is local by default, so assigning to a parameter does not rebind a variable in the caller:
def rename(name):
name = "Taylor"
person = "Sam"
rename(person)
print(person) # Sam
Python passes arguments by assignment: the function’s local parameter receives the object reference supplied by the caller. Rebinding that local name does not change the caller’s name. If the object is mutable, however, changing the object itself can be visible to the caller:
Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchWindows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstalldef add_item(items):
items.append("book")
things = []
add_item(things)
print(things) # ['book']
Python resolves names through local, enclosing, global, and built-in scopes. Assignments in a function are local by default; global and nonlocal explicitly rebind names in outer scopes. Prefer returning a result or passing an object to modify over using these declarations unless rebinding an outer name is intentional.
How arguments and defaults affect function calls
Parameters are the names in a definition; arguments are the values passed when calling it. Python supports positional and keyword arguments, as well as positional-only and keyword-only parameters.
Positional and keyword arguments
Positional arguments match parameters by order. Keyword arguments match them by name, which can make a call easier to read:
def describe(item, quantity):
return f"{quantity} × {item}"
first = describe("notebook", 3)
second = describe(item="notebook", quantity=3)
Optional parameters and defaults
A default lets a caller omit an argument. Default expressions are evaluated once, when Python executes the function definition—not afresh on every call.
Do these 3 things before closing this tab:
1Scan for outdated or missing drivers - takes under a minute2Repair Windows errors before they cause bigger problems3Fix the driver behind crashes, sound loss and screen glitchesdef greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
short = greet("Sam")
custom = greet("Sam", greeting="Welcome")
A mutable default such as a list is therefore shared across calls. This can preserve state unexpectedly:
Best Value
def add_tag(tag, tags=[]):
tags.append(tag)
return tags
Use None as the default when each call needs its own list or dictionary, then create that object inside the function:
def add_tag(tag, tags=None):
if tags is None:
tags = []
tags.append(tag)
return tags
Positional-only and keyword-only parameters
Use a slash (/) to mark preceding parameters positional-only, and an asterisk (*) to make following parameters keyword-only. Keyword-only arguments can make a call’s intent explicit; positional-only parameters can keep a parameter name from becoming part of the public calling interface.
def scale(value, /, *, factor=1):
return value * factor
result = scale(5, factor=2)
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.When to use a named function or lambda
Functions are objects: you can assign one to another name, pass it to another function, or return it from a function. Use a named def for logic that benefits from a descriptive name, multiple statements, or a docstring. A lambda is suited to a small, single expression, such as a short sorting key:
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →names = ["Mina", "Alex", "Bo"]
sorted_names = sorted(names, key=lambda name: len(name))
For logic that needs explanation or documentation, a named function is generally clearer.
For additional detail on argument terminology, calling conventions, and function behavior, see the Python Software Foundation’s Programming FAQ and the Python Glossary.
Quick Recap
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.

