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 gross_profit with its body missing. Watch the body get typed in, then
watch it run. This is real Python computing a real answer.
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.
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.
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.
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.