A function packages up logic so it can be reused by name — the same idea from Intro to Programming, defined in Python with the def keyword.
def greet(name):
return f"Hello, {name}!"
print(greet("Priya")) # "Hello, Priya!"def greet(name="Guest"):
return f"Hello, {name}!"
print(greet()) # "Hello, Guest!"
print(greet("Amit")) # "Hello, Amit!"Python lets you optionally annotate parameter and return types. These are not enforced at runtime — they're documentation and tooling support (your editor can catch a mismatch), not a hard rule the language checks when the function actually runs:
def add(a: int, b: int) -> int:
return a + b
print(add(2, 3)) # 5
print(add("2", "3")) # "23" — no error! type hints don't stop this at runtimeA Python function can return more than one value directly, separated by commas — under the hood, this is really returning a tuple (from the Tuples and Sets lesson):
def min_max(numbers):
return min(numbers), max(numbers)
low, high = min_max([4, 9, 1, 7])
print(low, high) # 1 9These let a function accept any number of arguments — *args collects extra positional arguments into a tuple, **kwargs collects extra named arguments into a dict:
def total(*numbers):
return sum(numbers)
print(total(1, 2, 3)) # 6
print(total(1, 2, 3, 4, 5)) # 15 — works with any number of arguments
def describe(**details):
for key, value in details.items():
print(f"{key}: {value}")
describe(name="Priya", course="Web Development")A string literal placed as the very first line inside a function becomes its docstring — Python's built-in way to document what a function does, retrievable at runtime instead of just sitting in a comment:
def greet(name):
"""Return a friendly greeting for the given name."""
return f"Hello, {name}!"
print(greet.__doc__) # "Return a friendly greeting for the given name."
help(greet) # shows the same text, formatted nicelyReal Python projects write one on every function that isn't completely obvious — this is closer to a formal expectation than a nice-to-have, and tools like Sphinx can generate full documentation pages straight from docstrings.