Python Function Trainer

Built-in AI tutor. Stuck on a step? Ask the helper on this page. It coaches, it does not hand you the answer.

A function is a named formula. In Excel you wrote =B2*C2 in a cell. In Python you write it once, give it a name, and call it as many times as you want. Scroll down: first see the parts of a function, then watch one get built and run, then build one yourself.

Step 1

The anatomy of a function

Every function has the same parts. Click a part below to light it up and read what it does.

def add2numbers(a, b):
    """Return the sum of a and b."""
    total = a + b
    return total

Click a part to inspect it.

function name argument / parameter return value docstring variable
Step 2

Watch one get built and run

Here is gross_profit with its body missing. Watch the body get typed in, then watch it run. This is real Python computing a real answer.


    
Step 3

Now you build them

Four functions, each a little harder than the last. Type the body, click Run to see what it does, then Check. Check runs tests, and some of them are hidden, so the function has to compute the answer rather than recognize one input. Every function needs a docstring: one plain sentence in triple quotes on the line under def.

What the last two added. safe_margin calls a function you already wrote instead of retyping its formula, and guards the inputs the way =IFERROR() does. That is the shape of safe_line_total in Lab 7. early_pay_amount has a default argument: rate=0.02 is used when the caller leaves it out. Homework 7 hands you a function with a default argument of its own.

Make an error on purpose

Before you finish, break something on purpose. Delete the colon at the end of a def line and click Run, or call a name you never defined. Read the traceback from its last line up, fix it, and run again. When an error appears, the Ask about this error button hands the error line to the tutor, and the tutor can see your code. The errors trainer walks through the six errors you will see most this week.

The vocabulary you are building. The line under def in triple quotes is the docstring. It says what the function does, and it is required in your own functions. The names in the parentheses are arguments (also called parameters). The value the function hands back is the return value. A name you create inside the body, like total, is a variable.