A Python function is a reusable named block of code defined with the def keyword. Functions split large scripts into small, testable units that accept inputs through parameters and send outputs back with return.
Keeping each function focused on one clear job makes your code easy to test, reuse, and read months later.
Parameters can define default values for optional arguments, and optional type hints document expected types for editors and linters.
def apply_discount(price: float, percent: float = 10.0) -> float:
"""Calculate final price after applying a percentage discount."""
discount = price * (percent / 100)
return round(price - discount, 2)
print(apply_discount(100)) # 90.0 (uses default 10%)
print(apply_discount(100, percent=25)) # 75.0 (keyword argument)
*args and **kwargsUse *args to accept any number of positional arguments as a tuple, and **kwargs to accept arbitrary keyword arguments as a dictionary.
def log_event(event_name: str, *tags: str, **details: object) -> None:
print(event_name, tags, details)
log_event("signup", "web", "promo", user_id=42, plan="pro")
items=[]: Python creates default objects once when defining the function, so mutated defaults leak across calls; use items: list | None = None instead.print() instead of return: Functions without return give back None, which breaks callers expecting a value.apply_discount(percent=20, 100) raises a SyntaxError.return statement?Python automatically returns None when execution reaches the end of the function body.
A parameter is the variable name in the def signature (price), while an argument is the actual value passed during the call (100).
No. Python ignores type hints at runtime, though tools like mypy, pyright, and VS Code check them statically before you run the code.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.