Originally published on my newsletter, The Path to AI FDE. Subscribe free to get each issue by email.
This is a “From Zero” issue. Last week your code learned to decide and repeat. Today you learn to name a piece of code and reuse it, so you write it once and call it whenever you need it.
That named piece of code is a function. You’ve already used other people’s functions: print(), len(), type(). Today you write your own. By the end you’ll have a small script that shares pizzas fairly between friends, built from two tiny functions.
Part A · Building a function
1. def defines a function; calling it runs it. Save this as greet.py in your sandbox folder:
def greet(name): print("Hello,", name) greet("Asha") greet("Ben") Run it with python3 greet.py (Windows: python greet.py):
Hello, Asha Hello, Ben The first two lines are the definition. def starts it, greet is the function’s name, (name) lists its inputs, and the line ends with a colon. The indented lines under it are the function’s body, just like the blocks in last week’s if and for.
Defining a function doesn’t run it. Python just remembers it under the name greet. The body runs only when you call the function: its name followed by brackets, greet("Asha"). Two calls, two greetings. Python reads your file from top to bottom, so put the def above the first line that calls it.
2. Parameters are the input slots; arguments are the values you put in them. A function can take more than one input:
def area(width, height): print(width * height) area(3, 4) area(10, 2) 12 20 width and height are the parameters: the names in the definition. 3 and 4 are the arguments: the values you pass when you call it. Python matches them in order, so the first argument goes into the first parameter. Inside the body, width is 3 and height is 4.
Leave one out, with area(3), and Python stops with:
TypeError: area() missing 1 required positional argument: 'height' The message names the slot you left empty. People mix up the two words all the time, and it rarely matters, but now you know which is which.
3. return sends a result back. Without it, you get None. Our area prints the answer, but the rest of your program can’t use it. Change print to return:
def area(width, height): return width * height total = area(3, 4) + area(10, 2) print(total) 32 return hands a value back to the line that called the function. You can picture area(3, 4) being replaced by 12, so the line becomes total = 12 + 20. That’s the difference: print shows a value to a human; return gives it to your code.
Forget return, and the function still runs but hands back None (Python’s “no value here” from issue #14):
def double(n): n * 2 result = double(5) print(result) None The function worked out 10 and then threw it away. return also ends the function immediately: any lines after it in the same block never run.
Part B · Functions that are easy to use
4. Defaults and keyword arguments let callers skip or name inputs. Give a parameter a default value with = in the definition, and callers can leave it out:
def make_tea(cups, sugar=1, milk=True): return f"{cups} cup(s), {sugar} sugar, milk: {milk}" print(make_tea(2)) print(make_tea(2, sugar=0)) print(make_tea(milk=False, cups=1)) 2 cup(s), 1 sugar, milk: True 2 cup(s), 0 sugar, milk: True 1 cup(s), 1 sugar, milk: False The first call uses both defaults. The second passes a keyword argument, sugar=0, which sets that one input by name. The third names every input, so the order no longer matters. Names make calls easier to read too: make_tea(2, sugar=0) says more than make_tea(2, 0). One rule: arguments without names come first. make_tea(sugar=0, 2) gives SyntaxError: positional argument follows keyword argument. Later in the series you’ll see the same shape in AI code, such as a function that splits text with a default size=500.
The one trap: never use a list as a default. The default is created once, when Python reads the def, and then shared by every call:
def add_item(item, basket=[]): basket.append(item) return basket print(add_item("apple")) print(add_item("pear")) ['apple'] ['apple', 'pear'] The second call “remembers” the apple. (append adds an item to the end of a list; lists get their own issue tomorrow.) The fix is to default to None and make a fresh list inside:
def add_item(item, basket=None): if basket is None: basket = [] basket.append(item) return basket Now the two calls print ['apple'] and ['pear'].
5. Scope: names made inside a function exist only inside it. Each call gets its own private workspace. Names created there disappear when the function ends:
def bake(): dough = 200 print("inside:", dough) bake() print(dough) inside: 200 NameError: name 'dough' is not defined (Python prints a few more lines above the NameError, called a traceback. You’ll learn to read those in issue #19.) The part of a program where a name exists is its scope. dough is a local name: it belongs to bake.
The other direction is softer: a function can read a name defined outside it. With greeting = "Hi" at the top of the file, a function can use greeting. But if a function assigns to a name, Python treats that name as local for the whole function. So this fails:
count = 0 def bump(): count = count + 1 bump() UnboundLocalError: cannot access local variable 'count' where it is not associated with a value The clean habit: pass values in as arguments and return results out.
def bump(n): return n + 1 count = 0 count = bump(count) count = bump(count) print(count) This prints 2. (Python has a global keyword that lets a function change an outside name. You’ll rarely need it; passing in and returning out is easier to follow.)
6. Give each function one job, and a name that says what it is. Small functions are easier to read, test and reuse. Here, one function does the maths and another builds the sentence:
def to_fahrenheit(c): """Convert Celsius to Fahrenheit.""" return c * 9 / 5 + 32 def describe(c): f = to_fahrenheit(c) return f"{c}°C is {f}°F" print(describe(100)) print(describe(-40)) print(to_fahrenheit(0) == 32) 100°C is 212.0°F -40°C is -40.0°F True Three habits are packed in here:
- One job each.
to_fahrenheitonly converts.describeonly words the answer, and it reusesto_fahrenheitinstead of repeating the formula. - A quick check.
to_fahrenheit(0) == 32printsTrue, so you know the maths is right. Because the function returns a value instead of printing it, it’s easy to test. That’s where proper tests (lesson 4.6) start. - A docstring. The string in triple quotes on the first line of the body says what the function does. Many editors show it when you hover over the name.
Give functions names that say what they do, in snake_case, the Python style guide’s choice for function names: to_fahrenheit, make_tea, add_item. If you can’t name a function without using “and”, it’s probably doing two jobs.
Try it (15 minutes)
- In your
sandboxfolder, createpizza.py, for sharing made-up pizzas between friends:
def slices_each(pizzas, people, per_pizza=8): """How many whole slices each person gets.""" return (pizzas * per_pizza) // people def leftover(pizzas, people, per_pizza=8): """How many slices are left after a fair share.""" return (pizzas * per_pizza) % people print(slices_each(3, 5), leftover(3, 5)) print(slices_each(2, 4, per_pizza=6), leftover(2, 4, per_pizza=6)) print(slices_each(people=7, pizzas=1)) - Run
python3 pizza.py. You should see:
4 4 3 0 1 Three pizzas of 8 slices is 24; shared by 5, that’s 4 each with 4 left over. (// and % are whole-number division and remainder, from issue #14.)
- Delete the word
returninslices_each(keep the maths) and run it again. The first number on each line becomesNone. Put it back. - Add
print(slices_each(3, 0))at the end. Read the last line of the error:ZeroDivisionError: integer division or modulo by zero. You can’t share between nobody. (Handling errors like this properly is issue #19.) Remove the line. - Write a third function,
pizzas_needed(people, slices_each=3, per_pizza=8), that returns how many pizzas to order. Hint:-(-a // b)rounds a division up. With 10 people, it should return4.
Check your understanding: (a) In def area(width, height):, are width and height parameters or arguments? (b) What does a function return if it has no return line? (c) Why did the second add_item("pear") call also show the apple?
Answer: (a) Parameters: the names in the definition. The values you pass in a call are the arguments. (b) None. (c) A list default is created once, when the def runs, and every call shares it. Use None as the default and make a new list inside.
Common beginner mistakes
- Forgetting
return, then wondering why the result isNone. - Printing inside a function when the caller needs the value. Return it, and print outside.
- Defining a function and never calling it (no brackets, no run).
- Using a list or dictionary as a default (
def f(x=[])). It’s shared between calls. - Trying to change an outside variable from inside a function. Pass it in and return the new value.
Takeaway
def names a block of code, and calling it runs it. Parameters are the input slots, and arguments are the values you put in. return hands a result back; without it you get None. Defaults and keyword arguments make calls short and clear. Names made inside a function stay inside. Keep each function to one job.
Where this fits in my roadmap: this is part of my on-ramp, the Python basics everything else sits on. Every AI app I build later is a stack of small functions: one to load text, one to call a model, one to check the answer. Tomorrow: lists and dictionaries, the two containers that hold almost all the data you’ll touch.
Over to you: what’s a task you’d turn into a function? Reply with its name and its inputs, like make_tea(cups, sugar=1).
Sources
- Python tutorial, “More Control Flow Tools”, Defining Functions (
def, the body is indented, a function withoutreturnreturnsNone; docstrings). https://docs.python.org/3/tutorial/controlflow.html#defining-functions - Python tutorial, “More Control Flow Tools”, More on Defining Functions (default argument values, “the default value is evaluated only once”, keyword arguments, positional arguments before keyword arguments). https://docs.python.org/3/tutorial/controlflow.html#more-on-defining-functions
- Python glossary, “parameter” and “argument” (the difference between the two). https://docs.python.org/3/glossary.html#term-parameter
- Python reference, “Execution model”, Naming and binding (a name assigned inside a function is local to it). https://docs.python.org/3/reference/executionmodel.html#naming-and-binding
- Python FAQ, “Why am I getting an UnboundLocalError when the variable has a value?” and “Why are default values shared between objects?”. https://docs.python.org/3/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value
- PEP 8, “Style Guide for Python Code” (function names are lowercase, with words separated by underscores). https://peps.python.org/pep-0008/#function-and-variable-names
- PEP 257, “Docstring Conventions” (what a docstring is; triple double quotes). https://peps.python.org/pep-0257/
- Python docs, “Built-in Exceptions” (
TypeError,NameError,UnboundLocalError,ZeroDivisionError). https://docs.python.org/3/builtins/exceptions.html
All examples are made up and were run with Python 3.13 on Nov 2, 2026. Error messages are from Python 3.13; other versions word some of them differently. Sources checked Nov 2, 2026.
Free: the 5-page roadmap from Novice to AI FDE.
If this was useful, subscribe to The Path to AI FDE for the next issue.








