Python has no special built-in function named X: function names are chosen by the person writing the program. A Python function is a reusable block of code, usually defined with def and run by calling its name; for example, def greet(): defines a function and greet() calls it.
What a function means in Python
A function packages instructions under a name so they can be run when needed. Instead of repeating the same steps throughout a program, you can put them in one function and call it from different places. Functions can also accept input and produce output, which makes them useful for organizing work into smaller, understandable parts.
The word function is sometimes used loosely for any named callable in Python. A function created with def is the most common kind, but Python also provides built-in functions such as print() and len(), and objects can be made callable by defining special behavior. In ordinary beginner code, however, learning to define and call a def function is the right starting point.
If you saw a particular expression such as x(), the name x alone does not reveal what it does. It might refer to a user-defined function, a function imported from a library, or another callable object. Look for where x is assigned or defined, and check its documentation. A variable named x is not automatically a function.
Defining and calling a function
Use the def keyword, a valid function name, parentheses, and a colon. The indented lines below the definition make up the function body. Python executes that body when the function is called, not merely when the definition is read.
def greet():
print('Hello!')
greet()
Here, greet is the function name. The final line calls it, so the program prints Hello!. Parentheses matter: writing greet without parentheses refers to the function object; writing greet() calls it. This distinction is useful when passing a function to another function, such as a callback.
Python uses indentation to mark the function body. Four spaces per indentation level is the standard convention. A missing colon or inconsistent indentation causes a syntax or indentation error, rather than defining the function as intended.
Parameters, arguments, and return values
A parameter is a name listed in a function definition; an argument is the value supplied when calling that function. Parameters let one set of instructions work with different input. A function can send a result back to its caller with return.
def rectangle_area(width, height):
return width * height
area = rectangle_area(5, 3)
print(area)
The parameters are width and height; the call supplies the arguments 5 and 3. The returned value is 15, which is assigned to area. return ends the function call and provides its result. By contrast, print() displays a value but does not, by itself, return that value to the caller.
A function can return more than one value syntactically. Python packages the expressions in a tuple, which can be unpacked into multiple names:
def min_and_max(values):
return min(values), max(values)
lowest, highest = min_and_max([4, 9, 2])
In this example, lowest becomes 2 and highest becomes 9. If execution reaches the end of a function without a return statement, Python returns None. The same is true of a bare return.
Common ways to pass arguments
Python supports several ways to supply arguments. Positional arguments are matched to parameters by their order, while keyword arguments identify a parameter by name. Keyword arguments can make a call easier to read, especially when a function accepts several options.
def describe_pet(name, animal='dog'):
return f'{name} is a {animal}.'
first = describe_pet('Milo')
second = describe_pet(name='Luna', animal='cat')
The animal parameter has a default value, so callers can omit it. In the first call, animal is 'dog'; in the second, keyword arguments set both values explicitly. Parameters without defaults generally need to be provided when calling the function. Positional arguments must not be placed after keyword arguments in a call.
For a function that needs to accept a varying number of arguments, *args collects extra positional arguments into a tuple, and **kwargs collects extra keyword arguments into a dictionary. These names are conventional rather than special; the asterisks provide the behavior.
def show_values(*args, **kwargs):
print(args)
print(kwargs)
show_values(3, 8, color='blue')
This call gives args the tuple (3, 8) and kwargs the dictionary {'color': 'blue'}. Use these flexible parameters when they genuinely help, such as when writing wrappers or APIs. For a small function with a known set of inputs, explicit parameter names are usually clearer.
Scope: where a function can see names
A function can use parameters and names assigned inside its body. A name created inside a function is normally local to that call, so code outside the function cannot use it as though it were a global variable. This separation prevents a function from accidentally changing unrelated values.
def make_message():
message = 'Ready'
return message
result = make_message()
message is local to make_message; result receives the returned string outside the function. A function can read a global name in some circumstances, but modifying global state can make programs harder to follow. Passing needed values as arguments and returning results usually makes dependencies clearer and testing easier.
Nested functions can also access names from an enclosing function. Python resolves names through nested scopes, then the module’s global scope, and finally built-ins. Keywords such as global and nonlocal allow assignment to names in outer scopes, but they should be used deliberately rather than as a substitute for clear inputs and outputs.
Defaults, type hints, and other useful features
Default parameter values are evaluated once, when the function is defined, not each time it is called. This is harmless for immutable defaults such as numbers and strings, but can surprise you if you use a mutable object such as a list. The list can then be shared across calls.
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
This pattern creates a fresh list when no list is supplied. Avoid a default such as items=[] when the function is meant to start with a new list on every call.
Type hints can document expected inputs and outputs:
def rectangle_area(width: float, height: float) -> float:
return width * height
These annotations can help readers, editors, and optional type-checking tools understand the intended types. Python does not generally enforce type hints at runtime, so this annotation does not automatically reject a string passed as width.
Python also has short anonymous functions written with lambda. A lambda contains a single expression, which is returned automatically. It can be handy for a brief key function, such as sorting records by one field, but a regular def is more suitable for multiple steps, a descriptive name, or documentation.
Common mistakes and how to avoid them
- Defining but never calling: A
defstatement creates the function, but its body does not run until something calls it. - Confusing printing with returning: Printed text appears for a person to see; a returned value can be stored, combined, or passed to another function.
- Forgetting parentheses:
calculaterefers to the function, whilecalculate()invokes it. Use the form that matches the purpose. - Using the wrong number of arguments: Python raises a
TypeErrorwhen required arguments are missing or too many are supplied, unless the function accepts flexible arguments. - Changing a mutable default: A list or dictionary used as a default can persist between calls. Use
Noneand create the object inside the function when you need a fresh one.
When debugging, read the traceback from the bottom for the exception type and message, then inspect the call site and function definition. A short function with a single responsibility is often easier to diagnose than a long function that handles unrelated tasks.
Choosing a good function design
Functions are most helpful when they give a meaningful name to a task, reduce duplicated logic, or isolate a calculation that deserves separate testing. A name such as calculate_shipping_cost communicates more than a generic name such as do_work. Names should use lowercase words separated by underscores, following Python’s common style convention.
Before extracting code into a function, consider what information it needs and what result it should produce. Prefer explicit parameters and a clear return value over relying on hidden global state. If a function has many parameters or does several unrelated jobs, that may indicate the task should be divided into smaller functions or represented with a class or data structure instead.
Functions are not limited to arithmetic. They can validate input, transform text, read data, or coordinate other operations. Some functions have side effects, such as writing a file or changing an object; documenting those effects helps callers understand what a call will do. A function that only computes and returns a result is often easier to reuse because its behavior depends more directly on its inputs.
Frequently Asked Questions
Is there an X function built into Python?
No standard built-in Python function is simply named X. The name may refer to a function in a particular program or library, or it may be a variable chosen by an author. Check the code or library documentation to identify its meaning.
How do I create a function in Python?
Write def, followed by a function name, parentheses, and a colon, then indent the body. For example, def double(number): return number * 2 defines a function; call it as double(4).
What is the difference between a parameter and an argument?
A parameter is the name in a function definition, such as number in def double(number):. An argument is the value supplied in a call, such as 4 in double(4).
What happens if a function has no return statement?
It returns None when it finishes. If the function prints a value, that output does not change the return value; printing and returning serve different purposes.
Can a Python function return multiple values?
Yes. Write multiple expressions after return, and Python returns them together as a tuple. You can unpack that tuple into separate variables at the call site.
Related
- Split Feature in SOLIDWORKS: What It Does and How
- Split in SQL Server: STRING_SPLIT and Practical Examples
- SQL Split Syntax: Split Strings by Delimiter
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Calculate a Weighted Average in Excel: Formula and ExamplesTo calculate a weighted average in Excel, multiply each value by its weight, add those products, and divide…
- Weighted Average in Excel: Formulas, Examples, and TipsTo calculate a weighted average in Excel, multiply each value by its weight, add those products, and divide…
- Excel IFS Function: Formula, Examples, and TipsIn Excel, the IFS function checks conditions in order and returns the value paired with the first condition…
- Excel ROUND DOWN to Whole Number: Formulas and ExamplesTo round a number down to a whole number in Excel, use ROUNDDOWN with zero decimal places. If…
- SUBTOTAL Formula Usage in Excel: Filters and ExamplesIn Excel, use the SUBTOTAL formula to calculate a sum, average, count, or other summary while automatically ignoring…
- Excel UPPER Function: How to Make Text All CapsExcel’s uppercase text function is UPPER. In Microsoft Excel for Microsoft 365, enter =UPPER(A2) to convert the text…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.