Python: warming up...

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 line_total with its body missing. Watch the body get typed in, then actually run — this is real Python, computing a real answer.


    
Step 3

Now you build one

Your turn You write the body this time. Type it, Run it, then Check it.

Type the body, click Run to see what it does, then Check to run hidden test cases. The output is real Python, running right here in your browser.

Task.
Output
Click Run to execute your code.
Want to see an error? Change your return to return a + str(b) and Run it. Python refuses to add a number and a string, and the red traceback tells you exactly that.

Make an error on purpose

Before you finish, break something so the red stops being scary. Delete the colon at the end of the def line and click Run, or call a name you never defined. Read the traceback bottom-up, fix it, and run again. Every working programmer reads tracebacks all day. It is diagnosis, not failure.

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.