Python functions model reusable behavior. They take inputs, perform a focused task, and return a result or intentional side effect.
This page is different from classes: functions are best for stateless actions; classes are best when state and behavior live together over time.
A function turns repeated logic into a named unit that can be tested and reused. Good function names explain the task.
Parameters describe what the function needs. Return values describe what the caller gets back. Clear boundaries make code easier to test.
Functions are easiest to reason about when they depend mostly on parameters. File writes, network calls, and database updates should be obvious from the function name or design.
Python functions can accept required arguments, default arguments, extra positional arguments with *args, and extra keyword arguments with **kwargs.
Use the simplest argument shape that communicates the job. Flexible arguments are useful for wrappers and utilities, but they can make beginner code harder to inspect.
def build_profile(name, role="student", *skills, **details):
profile = {
"name": name,
"role": role,
"skills": list(skills),
"details": details,
}
return profile
user = build_profile("Maya", "developer", "Python", "SQL", city="Pune")
print(user["skills"])
print(user["details"]["city"])
['Python', 'SQL']
Pune
role has a default value, *skills collects extra skill names, and **details collects named extra data such as city.
def calculate_invoice_total(items, tax_rate=0.18):
subtotal = sum(item["price"] * item["quantity"] for item in items)
return round(subtotal + subtotal * tax_rate, 2)
0 of 2 checked
Try this next
0 of 3 completed
*args collects extra positional arguments into a tuple. **kwargs collects extra keyword arguments into a dictionary. You can use both: def func(*args, **kwargs). They allow functions to accept any number of arguments.
A decorator is a function that takes another function and extends its behavior. Applied with @decorator_name syntax. Common uses: @staticmethod, @classmethod, @property, @functools.lru_cache for memoization.
A function is defined at module level with def. A method is a function defined inside a class. Methods automatically receive the instance (self) or class (cls) as the first argument.
Explore 500+ free tutorials across 20+ languages and frameworks.