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.

Cover card titled "Functions, from Zero" for issue 16 of The Path to AI FDE by Dhanush Kumar Sivaji. Subtitle: write it once, name it well, use it everywhere. Six numbered cards in two lanes. Part A, building a function: 1, def and calls, shown as def greet(name): with print("Hello,", name) indented below: def stores the code, and a call, greet("Asha"), runs it; 2, parameters, shown as width, height receiving 3, 4: parameters are the input slots and arguments are the values you pass; 3, return, shown as return width * height: hands a result back to your code, with a warning that no return gives None. Part B, easy to use: 4, defaults and keywords, shown as make_tea(2, sugar=0): callers can skip inputs or name them, with a warning never to use a list as a default; 5, scope, shown as inside, then stays inside: pass values in as arguments and return results out; 6, one job each, shown as to_fahrenheit(c): small, well-named functions are easy to test and reuse. A tip bar says: arguments go in, a return value comes out.

Part A · Building a function

Diagram titled "def defines, a call runs", subtitle: write it once, run it whenever you need it. Left panel, the definition, stored but not run: the line def greet(name): is split into labelled tiles: def is the keyword, greet is the name, name in brackets is the parameter or input, and the line ends with a colon. Below it, the indented body print("Hello,", name) in a dashed box; the indented lines are the body, which Python remembers under the name greet. Right panel, the calls, each of which runs the body: greet("Asha") leads to Hello, Asha and greet("Ben") leads to Hello, Ben; a call is the name followed by brackets, so no brackets means no run. Below, greet.py shows the full code and its two lines of output. Two notes: Python reads the file top to bottom, so put the def above the first call; and print(), len() and type() are functions too. A tip bar says def writes the recipe, and a call cooks it as many times as you like.

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.

Diagram titled "Parameters and arguments", subtitle: a function is a machine with named input slots. Two machines labelled area(width, height). In the first, the arguments 3 and 4 drop into the slots named width and height, so width = 3 and height = 4, and it prints 12. In the second, 10 and 2 go in and it prints 20. Labels mark the values you pass as arguments and the names in the def as parameters. Below, area.py shows the code and the output 12 and 20. A note says arguments are matched in order: the first argument goes into the first parameter. An orange box, an empty slot: area(3) gives TypeError: area() missing 1 required positional argument: 'height'. A tip bar says parameters are the slots in the definition, and arguments are what you put in them.

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.

Diagram titled "return sends a value back", subtitle: print is for people, return is for your code. Left, the call is replaced by its answer, in three steps: total = area(3, 4) + area(10, 2); each call returns its value, giving total = 12 + 20; then the line finishes, giving total = 32. Right, area.py version 2 uses return width * height and prints 32. Three cards below: print shows a value to a human on screen, and your code can't use it afterwards; return hands a value back to your code to store or use, and ends the function at once; no return: def double(n): n * 2, then print(double(5)) shows None. A tip bar says forget return and the function still runs, but hands back None.

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

Diagram titled "Defaults and keyword arguments", subtitle: let callers skip an input, or name it. The definition def make_tea(cups, sugar=1, milk=True): with three calls: make_tea(2) gives 2 cup(s), 1 sugar, milk: True, using both defaults; make_tea(2, sugar=0) gives 2 cup(s), 0 sugar, milk: True, with one input set by name, a keyword argument; make_tea(milk=False, cups=1) gives 1 cup(s), 1 sugar, milk: False, with every input named so order doesn't matter. One rule: arguments without names come first; make_tea(sugar=0, 2) gives SyntaxError: positional argument follows keyword argument. An orange warning, never a list as a default, because it's made once and shared by every call: add_item with basket=() returns ('apple') the first time and ('apple', 'pear') the second. A green fix: default basket to None and make a new list inside, which gives ('apple') then ('pear'). A tip bar says names make calls readable: make_tea(2, sugar=0) says more than make_tea(2, 0).

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'].

Diagram titled "Scope: what a function can see", subtitle: every call is a room, and what's made inside stays inside. Left, a dashed lavender box marked inside bake(), local names: def bake(): sets dough = 200 and prints inside: 200. Outside the function, bake() then print(dough) gives NameError: name 'dough' is not defined. Right, a green box, reading an outside name works: greeting = "Hi" and a function welcome(name) that returns greeting + ", " + name prints Hi, Asha. An orange box, assigning makes it local: count = 0 and a function bump() that runs count = count + 1 gives UnboundLocalError: cannot access local variable 'count' where it is not associated with a value. Below, the clean pattern: def bump(n): return n + 1, and count = bump(count) twice prints 2; the function never touches the outside name, it gets a value and hands back a new one. A tip bar says each call gets its own workspace: arguments in, return value out.

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.)

Diagram titled "One job per function", subtitle: small, well-named functions are easier to read, test and reuse. Left, an orange box, one function with two jobs: report(c) converts Celsius to Fahrenheit and prints the sentence, so you can't reuse the number or check it. Below, good names say what the function does, in snake_case: to_fahrenheit, make_tea, add_item; if you need "and" to name it, it's doing two jobs. Right, a green box, two small functions with one job each: to_fahrenheit(c) has the docstring "Convert Celsius to Fahrenheit." and returns c * 9 / 5 + 32; describe(c) calls it and returns a sentence. The output is 100°C is 212.0°F, -40°C is -40.0°F and True, the last from the quick check to_fahrenheit(0) == 32. Tags: docstring says what it does, describe reuses it, a quick check. A tip bar says a function that returns a value is easy to test, and that's where proper tests start.

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_fahrenheit only converts. describe only words the answer, and it reuses to_fahrenheit instead of repeating the formula.
  • A quick check. to_fahrenheit(0) == 32 prints True, 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)

  1. In your sandbox folder, create pizza.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)) 
  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.)

  1. Delete the word return in slices_each (keep the maths) and run it again. The first number on each line becomes None. Put it back.
  2. 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.
  3. 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 return 4.

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 is None.
  • 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

  1. Python tutorial, “More Control Flow Tools”, Defining Functions (def, the body is indented, a function without return returns None; docstrings). https://docs.python.org/3/tutorial/controlflow.html#defining-functions
  2. 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
  3. Python glossary, “parameter” and “argument” (the difference between the two). https://docs.python.org/3/glossary.html#term-parameter
  4. 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
  5. 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
  6. 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
  7. PEP 257, “Docstring Conventions” (what a docstring is; triple double quotes). https://peps.python.org/pep-0257/
  8. 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.