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.
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.
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.
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.
return a + str(b) and Run it. Python
refuses to add a number and a string, and the red traceback tells you exactly that.
These inputs are held out — they are not in the editor, so you cannot hard-code the answers. The function has to actually compute them.
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.
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.