Section650

Writing

TopicLearning
Reading6 min

Functions Explained With Homemade Pizza and Pancakes

A function turns input into output through a set of instructions. A beginner’s guide to parameters, return values, side effects, defaults and naming, using homemade pizza and pancakes in current Python.

By Ka Lun Chan · Learning

What is a function in programming?

A function is a named set of instructions that turns input into output. You give it something, it follows its steps, and it hands something back. People work the same way: we feel something (input) and respond to it (output).

I first wrote this on my old blog. This version keeps the pizza and pancakes, fixes the code that didn’t run, and rewrites it in the Python you’d write today.

The idea that made functions click for me is simple: write a function for any routine you use often. If you make the same thing every day, you want the recipe written down once, not reinvented each morning. The table below maps each idea in this post to the kitchen and to the code.

Fig. 631-1 Function concepts in the kitchen and in Python
ConceptPizza analogyCode
ParameterThe ingredients you hand the cookingredients: list[str]
Function bodyThe recipe the cook followsthe indented block under def
Return valueThe pizza that comes out of the ovenreturn [...]
Default argumentBake for 20 minutes unless told otherwiseminutes: int = 20
Side effectTelling the whole kitchen what you’re doingprint(...)
Pure functionSame ingredients in, same pizza out, nothing else touchedadd_and_mix(ingredients)
ReusePizza dough and pancake batter both start in the mixing bowlboth call add_and_mix
NameA recipe title that says what you getmake_pizza, not mp or do_stuff

What does a simple function look like?

It starts with def, a name and parentheses for the input, then an indented body of steps, and usually ends with return to hand back the result. Here’s the original idea: make a really, really good homemade pizza every day.

Python: the daily pizza
def make_pizza() -> str:
    """Make a really, really good homemade pizza."""
    print("Preheat the oven")
    print("Make your own pizza dough")
    print("Add homemade salsa as a base for your pizza sauce")
    print("Add some homegrown produce")
    print("Add the pork")
    print("Load your pizza with cheddar cheese")
    print("Bake in the preheated oven for 20 minutes")
    return "delicious pizza"


dinner = make_pizza()  # prints seven steps, then dinner == "delicious pizza"

Every function you write has the same three parts. A good name like make_pizza tells you what you’ll get. The indented body is the recipe, and the return line is the output, which the caller can store in a variable, as dinner does here.

Right under the def line sits a docstring. The Python tutorial says its first line should be a short summary that starts with a capital letter and ends with a period. Editors show it when you hover over the function, so it’s the first thing the next person reads.

Next, -> str is a type hint saying the function returns a string. Python doesn’t enforce it at runtime. It documents intent, and tools like editors and type checkers use it to catch mistakes before you run anything.

What was wrong with the original code?

Three things. The quotes were curly typographic quotes, so the code failed with a syntax error when pasted. The helper returned print(...), which is always None. And every function printed its steps instead of returning them, which made the results hard to test or reuse.

Those curly quotes came from the blog editor rather than the code, but that’s a lesson in itself: Python only accepts straight quotes, and copying code from a formatted page is a classic beginner trap.

Returning print(...) is the more interesting bug. print writes to the screen and returns None, and as the tutorial explains, a function that falls off the end, or calls return with no value, returns None. So this looked like it worked, because the text appeared, but the caller received nothing useful:

Python: the original helper, quotes fixed
def add_and_mix(*ingredients):
    return print("Add {} ingredients and mix in a bowl".format(len(ingredients)))

result = add_and_mix("flour", "milk")
# Add 2 ingredients and mix in a bowl
print(result)
# None

The original also used *ingredients, which collects any number of arguments into a tuple. That’s valid Python, but for a list of ingredients it’s clearer to pass one list. You can see what’s going in, and you can build the list somewhere else and hand it over. The old .format() calls still work too. F-strings are just shorter and put the value where you read it.

How do functions help you reuse code?

Move the steps two recipes share into their own function, and call it from both. Pizza dough and pancake batter both start by mixing ingredients in a bowl, so that step becomes add_and_mix, written once and used twice.

Eating pizza every day gets old. The original post added pancakes with different ingredients, and noticed the duplicated step. Duplication is a waste: it makes code harder to maintain and gives bugs more places to hide. I wrote more about that in the programming principles every developer should know. Here’s the refreshed version, with each function returning its steps:

Python: kitchen.py
def add_and_mix(ingredients: list[str]) -> str:
    """Describe mixing the ingredients in a bowl.

    >>> add_and_mix(["flour", "milk", "eggs"])
    'Mix 3 ingredients in a bowl: flour, milk, eggs'
    """
    return f"Mix {len(ingredients)} ingredients in a bowl: {', '.join(ingredients)}"


def make_pizza(ingredients: list[str], minutes: int = 20) -> list[str]:
    """Return the steps for a homemade pizza.

    >>> make_pizza(["olive oil", "salt", "sugar"])[-1]
    'Bake for 20 minutes'
    >>> make_pizza(["salt"], minutes=12)[-1]
    'Bake for 12 minutes'
    """
    return [
        "Preheat the oven",
        "Make the pizza dough",
        add_and_mix(ingredients),
        "Add homemade salsa, homegrown produce, pork and cheddar",
        f"Bake for {minutes} minutes",
    ]


def make_pancakes(ingredients: list[str]) -> list[str]:
    """Return the steps for a stack of pancakes.

    >>> make_pancakes(["flour", "milk"])[0]
    'Mix 2 ingredients in a bowl: flour, milk'
    """
    return [
        add_and_mix(ingredients),
        "Heat the pan and add oil",
        "Pour the batter into the pan",
        "Flip when the bubbles burst",
    ]


if __name__ == "__main__":
    for step in make_pizza(["olive oil", "salt", "sugar"]):
        print(step)

The lines starting with >>> inside the docstrings are doctests: examples that double as tests. Python’s doctest module runs them and compares the output:

Shell
python3 -m doctest -v kitchen.py   # runs every >>> example in the docstrings
python3 kitchen.py                 # prints the pizza steps

Now if you change how mixing works, you change it in one place and both recipes pick it up. When you later find two functions that have grown the same steps, pulling them into a shared helper is one of the most common moves in refactoring.

What is a side effect, and why avoid it inside functions?

A side effect is anything a function does besides returning a value: printing, writing a file, changing a variable outside itself, calling an API. A pure function has none, and gives the same output for the same input every time, which makes it easy to test and reuse.

In the kitchen, a pure function is a cook who takes the ingredients and hands back a pizza without touching anything else. A cook who also shouts every step across the room is producing a side effect. That’s fine when you want the shouting, but you can’t easily check the pizza without hearing it, and you can’t make a quiet pizza.

That’s why the refreshed add_and_mix, make_pizza and make_pancakes return values and don’t print. The printing happens once, at the edge, in the if __name__ == "__main__": block. Real programs need side effects, since saving data and showing output are the point. Keeping them at the edges and the logic in pure functions is a habit worth building early.

How should you name functions and use default arguments?

Name a function for what it does, usually starting with a verb, in lowercase with underscores, as PEP 8 recommends. Use a default argument for a value that’s usually the same, like the 20-minute bake, and never use a mutable value such as a list as a default.

PEP 8 says function names should be lowercase, with words separated by underscores where that helps readability, and variable names follow the same rule. make_pizza tells you what you’ll get. mp, pizza_func or process make the reader open the function to find out.

The minutes: int = 20 parameter means callers can write make_pizza(ingredients) for the usual bake or make_pizza(ingredients, minutes=12) for a thin crust. The trap is that Python evaluates a default only once, when the function is defined. A list default gets shared between calls, so toppings from one pizza end up on the next:

Python: the mutable default trap
# Wrong: the same list is reused on every call
def add_topping(topping: str, toppings: list[str] = []) -> list[str]:
    toppings.append(topping)
    return toppings

# Right: use None and create a new list inside
def add_topping(topping: str, toppings: list[str] | None = None) -> list[str]:
    if toppings is None:
        toppings = []
    toppings.append(topping)
    return toppings

If AI can write functions, do you still need to understand them?

Yes. An AI assistant will write make_pizza in seconds, but you still have to read it and decide whether it returns what you need, whether it hides a side effect, and whether its tests check anything real.

Every bug in the original post is the kind that’s easy to miss on a quick read: output that appears on screen while the function returns None, or a default that quietly leaks between calls. Generated code makes the same kinds of mistakes, and it looks just as confident either way. If you’re learning, write the small functions yourself first and use the assistant to explain and review them. I go into how in using AI to learn a skill instead of offloading the work.

Once functions feel natural, the next step is grouping related data and functions together, which is what thinking in objects covers.

Sources

Checked in November against the Python tutorial’s sections on defining functions, default arguments, arbitrary argument lists, docstrings and annotations, PEP 8, PEP 484 and the doctest documentation. The final code was run and its doctests pass. The analogy and the recipes are mine.

Short answers

What is a function in programming?

A named set of instructions that turns input into output. You pass it values as arguments, it runs its steps, and it hands back a result with return. Write one for any routine you use often, so the steps live in one place.

What is the difference between print and return in Python?

print writes text to the screen and gives back None. return hands a value back to whoever called the function, so it can be stored, tested or passed on. A function that only prints, or that returns print(...), returns None.

What is a pure function?

A function with no side effects that gives the same output for the same input every time. It doesn’t print, write files or change anything outside itself, which makes it easy to test and reuse. Keep side effects such as printing at the edges of a program.

Why shouldn’t you use a list as a default argument in Python?

Python evaluates a default value once, when the function is defined, so a list default is shared between calls and keeps what earlier calls added. Use None as the default and create a new list inside the function.

Write one routine down

Pick something you do the same way every week, write it as a function that returns its result, and add one doctest. Then ask what it would take to make it serve a second recipe.

Tell me what you’re building