Functions: Write It Once, Use It Everywhere
Turn repeated steps into functions with inputs and outputs, and test them with known answers.
Objective
By the end of this lesson, you can write a function, give it inputs, return a result, and test it against an answer you already know.
What a function is
A function is a named set of steps. You give it inputs (called parameters). It gives back an output with return.
def f_to_c(temp_f):
return (temp_f - 32) * 5 / 9
def starts the function. temp_f is the input. Now you can call f_to_c(212) anywhere instead of retyping the formula.
Why engineers care
Machine learning projects repeat the same steps many times: clean a value, convert a unit, score a prediction. Functions keep those steps in one place. If there is a bug, you fix it once.
Test with known answers
A good habit: test a function with inputs where you already know the answer. Water boils at 212 F (100 C) and freezes at 32 F (0 C).
cutoff=100 is a default value. If you do not pass a cutoff, the function uses 100. Making the cutoff an input, instead of hiding it inside, makes the decision visible.
A national example
Judgment check
A function hides its steps. That is useful, but it can hide decisions too. If a function decides something about people (eligible or not, risky or not), put the cutoffs in the inputs and write a comment explaining where they came from.
Good function habits
0 of 4 doneDiscussion
Ask. Answer. Build together.
Loading…