A function groups instructions that perform one task, so you can call that task whenever it is needed instead of copying the same code. This supports the DRY principle: avoid repeating yourself. In data work, a function can turn a repeated workflow—such as generating model metrics—into a named, reusable operation. section 3.2 section 3.2.2
Evaluate several classification models
Customer-churn experiments may compare logistic regression, random forest, and gradient boosting. Rather than rewrite prediction and precision, recall, and accuracy checks for every model, define a helper such as get_metrics(model, train_features, test_features, train_labels, test_labels). Call it once per fitted model, or iterate through a collection of models. Passing the data as parameters also lets the same function evaluate different training or test subsets. section 3.2.2
Listing 3.20 This code snippet shows how we can create a helper function to get the performance metrics for any of the classification models we’re testing.
def get_metrics(model, #1
train_features, #1
test_features, #1
train_labels, #1
test_labels): #1
train_pred = model.predict(train_features) #2
test_pred = model.predict(test_features) #2
print("Printing metrics summary...") #3
print("Train Precision = ", #4
metrics.\ #4
precision_score(train_labels, train_pred)) #4
print("Train Recall = ", #4
metrics.\ #4
precision_score(train_labels, train_pred)) #4
print("Train Accuracy = ", #4
metrics.\ #4
accuracy_score(train_labels, train_pred)) #4
print("Test Precision = ", #5
metrics.\ #5
precision_score(test_labels, test_pred)) #5
print("Test Recall = ", #5
metrics.\ #5
precision_score(test_labels, test_pred)) #5
print("Test Accuracy = ", #5
metrics.\ #5
accuracy_score(test_labels, test_pred)) #5
return "...Metrics summary complete" #6
The listing makes the function boundary concrete: inputs identify the model and datasets, while the body produces predictions and prints metrics. section 3.2.2
Functions also provide building blocks for modular code. Give separate tasks separate functions—for example, read data, cap outliers, and clean data—then let a higher-level function call the smaller ones. Keeping these functions in a script makes them portable: another script can import and use a selected function without running the protected main execution block. section 3.3.1
Make a function easier to use and maintain by:
- Choosing a focused task and a descriptive name, rather than using one long repeated code block. section 3.2 section 3.3.1
- Accepting the values the task needs as parameters, so the function can be reused with different models or datasets. section 3.2.2
- Adding type hints to document expected parameter and return types, such as def add(a: int, b: int) -> int. section 3.4
- Validating inputs when needed. Type hints communicate expectations but do not prevent unsuitable values; isinstance checks can raise a TypeError before the function continues. section 3.4
Hints versus checks
An unannotated add(a, b) can join two strings as easily as it adds numbers. Adding int annotations signals that numeric inputs and output are expected. Adding isinstance checks and raising TypeError supplies actual enforcement when integer-only behavior matters. section 3.4
Practice by defining a create_plots function with a pandas data frame, integer plot type, and color input, then annotate its inputs and list output. Add validation that raises an error before execution when an input has the wrong type. Functions are one alternative to repetitive code; built-in methods and dictionaries can also simplify repeated patterns or long if-else blocks. section 3.8 section 3.9

























