Function Basics in Python

From the Python cheat sheet ยท Functions ยท verified Jul 2026

Function Basics

Define functions with parameters, defaults, and return values.

python
def greet(name, greeting="Hello"):
    """Return a greeting string."""
    return f"{greeting}, {name}!"

result = greet("Alice")
result = greet("Bob", greeting="Hi")
๐Ÿ’ก Use / to mark positional-only params, * to mark keyword-only params
โšก Functions can return multiple values as a tuple โ€” unpack with a, b = func()
๐Ÿ“Œ Default arguments are evaluated once โ€” never use mutable defaults like def f(x=[])
๐ŸŸข Add docstrings as the first line in a function for documentation
functionsparametersreturn

More Python tasks

Back to the full Python cheat sheet