Python Functions: Parameters, Return Values, Scope and Lambdas
What is a function in Python?
A function in Python is a named, reusable block of code defined with def. It takes inputs called parameters, runs its body when called, and sends a result back with return; without a return it gives back None. Functions are objects, so you can store them in variables, pass them to other functions and return them.
Defining and calling a function
The def line names the function and lists its parameters. When you call it, the values you pass are the arguments. The indented body runs only when the function is called.
def gst_amount(price: float, rate: float = 18.0) -> float:
"""Return the GST on a price, using a percentage rate."""
return price * rate / 100
print(gst_amount(1000)) # 180.0
print(gst_amount(1000, 5)) # 50.0
print(gst_amount(rate=12, price=500)) # 60.0
help(gst_amount) # shows the docstring- Positional arguments are matched by order.
- Keyword arguments are matched by name, so order does not matter.
- Default values make a parameter optional.
- A docstring is the first string in the body. It documents the function and is shown by
help()and by editors.
If variables and loops are new to you, start with Python basics before this guide.
Return values: one, several or none
return ends the function immediately and hands back a value. To return several values, return a tuple and unpack it. A function that reaches the end without return returns None.
def min_max(numbers: list[int]) -> tuple[int, int]:
return min(numbers), max(numbers)
low, high = min_max([42, 7, 19])
print(low, high) # 7 42
def log(message: str) -> None:
print(f"[log] {message}")
print(log("saved")) # prints [log] saved, then None The mutable default argument pitfall
Default values are evaluated once, when the def line runs, not on every call. If the default is a mutable object such as a list, every call that uses the default shares the same list.
def add_item_bad(item, basket=[]):
basket.append(item)
return basket
print(add_item_bad("pen")) # ['pen']
print(add_item_bad("book")) # ['pen', 'book'] surprise!
def add_item(item, basket=None):
if basket is None:
basket = []
basket.append(item)
return basket
print(add_item("pen")) # ['pen']
print(add_item("book")) # ['book']Use None as the default and create the new object inside the function. This applies to lists, dicts and sets. Why lists behave this way is explained in our Python data types guide under mutability.
Flexible arguments: *args and **kwargs
*args collects any extra positional arguments into a tuple, and **kwargs collects extra keyword arguments into a dict. The names are conventions; the asterisks do the work. The same asterisks unpack a list or dict when calling.
def total(*args: float) -> float:
return sum(args)
def profile(name: str, **kwargs: str) -> str:
extras = ", ".join(f"{k}={v}" for k, v in kwargs.items())
return f"{name} ({extras})"
print(total(10, 20, 30)) # 60
print(profile("Kiran", city="Jaipur", role="dev"))
# Kiran (city=Jaipur, role=dev)
nums = [1, 2, 3]
opts = {"city": "Noida"}
print(total(*nums), profile("Asha", **opts))
def connect(host: str, *, port: int = 22) -> str:
return f"{host}:{port}" # port must be passed by keyword
print(connect("example.com", port=2222))A bare * in the parameter list makes every parameter after it keyword-only, which keeps calls readable when there are several options.
Scope and the LEGB rule
When Python looks up a name, it searches four scopes in order, known as LEGB:
- Local: names assigned inside the current function.
- Enclosing: names in any outer function that wraps the current one.
- Global: names at the top level of the module.
- Built-in: names Python provides, such as
lenandprint.
rate = 5 # global
def make_counter():
count = 0 # enclosing for inner()
def inner():
nonlocal count # rebind the enclosing name
count += 1
return count
return inner
counter = make_counter()
print(counter(), counter()) # 1 2
def show_rate():
return rate # reads the global
print(show_rate()) # 5Reading an outer name works automatically, but assigning to it creates a new local name unless you declare nonlocal or global. Relying on global makes code hard to follow, so pass values in as arguments and return results instead.
Lambda functions and functions as values
A lambda is a small anonymous function limited to a single expression. It is most useful as a short argument to functions like sorted(), max() and filter().
students = [("Ravi", 72), ("Meera", 91), ("Arjun", 85)]
by_marks = sorted(students, key=lambda s: s[1], reverse=True)
print(by_marks[0]) # ('Meera', 91)
evens = list(filter(lambda n: n % 2 == 0, range(10)))
print(evens) # [0, 2, 4, 6, 8]Docstrings and type hints
Every public function should start with a docstring that says what it returns and any exceptions it raises. Type hints such as list[int], dict[str, float] and str | None describe expected types. Python stores them in __annotations__ but does not check them at run time; tools such as mypy or your editor read them to catch mistakes before you run the code.
If a lambda grows hard to read, or you want to give it a name, write a normal def instead. Functions can also live inside classes as methods; see object-oriented Python.
Practical exercise: a marks report module
Create report.py with the following functions, each with a docstring and type hints:
average(*marks: float) -> floatthat raisesValueErrorwhen no marks are passed.grade(mark: float, *, pass_mark: float = 40) -> strreturning "pass" or "fail".add_result(name: str, mark: float, results: dict[str, float] | None = None) -> dict[str, float]that avoids the mutable default pitfall.- A
main()function that builds results for three students, sorts them with a lambda and prints a report, called underif __name__ == "__main__":.
- Done looks like this:
average(60, 80)returns70.0, two separate calls toadd_resultwithout a dict return two independent dicts, andhelp(grade)shows your docstring. - Extension: run
mypy report.pyafterpip install mypyand fix any type errors it reports.
For more practice structuring code, compare this approach with the one in procedural vs object-oriented programming. The PHP Foundation course teaches functions in PHP with the same principles.
Common mistakes
- Using a list or dict as a default argument, so data leaks between calls.
- Forgetting
returnand then using theNonethe function gives back. - Assigning to a global name inside a function and getting
UnboundLocalErrorwhen the same name is read earlier in that function. - Writing long, multi-step logic inside a lambda instead of a named function.
- Treating type hints as checks; Python does not enforce them at run time.
Frequently asked questions
What is the difference between a parameter and an argument?
A parameter is the name in the function definition, such as price. An argument is the actual value passed in a call, such as 1000.
Does Python pass arguments by value or by reference?
Neither exactly. Python passes a reference to the object, sometimes called pass by assignment. Changing a mutable argument in place affects the caller's object, but rebinding the parameter name inside the function does not.
What is a decorator?
A decorator is a function that takes a function and returns a new one, applied with the @name syntax above a def. It works because functions are ordinary objects, and is commonly used for logging, caching and access checks.