← All cheat sheets

Python functions cheat sheet 🧩

def, return, default and keyword arguments, *args, lambda and scope. Every snippet runs in your browser, and the page prints on one sheet.

Define and call

def greet(name):
    return f"Hello, {name}!"

print(greet("Ada"))

return sends a value back. A function with no return gives None.

Defaults and keywords

def price(amount, vat=0.2):
    return round(amount * (1 + vat), 2)

print(price(10))
print(price(10, vat=0.05))

Parameters with defaults go after the ones without.

Return several values

def stats(nums):
    return min(nums), max(nums), sum(nums) / len(nums)

low, high, mean = stats([4, 9, 2])
print(low, high, mean)

Python packs them into a tuple and you can unpack them.

Any number of arguments

def total(*nums):
    return sum(nums)

def show(**info):
    for k, v in info.items():
        print(k, "=", v)

print(total(1, 2, 3))
show(name="Ada", role="engineer")

*args collects extra positional arguments, **kwargs extra keyword ones.

lambda

words = ["banana", "fig", "cherry"]
print(sorted(words, key=lambda w: len(w)))
double = lambda n: n * 2
print(double(21))

A small one-line function, mostly used as a key for sorting.

Scope

count = 10

def add_one(n):
    n = n + 1
    return n

print(add_one(count), count)

Variables made inside a function stay inside it. Pass values in and return results out.

Docstrings and type hints

def area(width: float, height: float) -> float:
    """Return the area of a rectangle."""
    return width * height

print(area(3, 4.5))
print(area.__doc__)

Hints document what you expect; Python does not enforce them.

Start the free lessons More cheat sheets