Chapter 5: Functions in Python – Writing Reusable AI Code

Introduction

Functions are one of Python’s most powerful features, enabling code reuse, organization, and readability. In AI workflows, functions help modularize data preprocessing, model training, and inference. This chapter covers defining functions, function arguments, lambda functions, and best practices to ensure clean and efficient AI code.


Defining Functions – The Building Blocks of AI Workflows

1️⃣ Basic Function Syntax

A function is defined using the def keyword:

def greet(name):
    return f"Hello, {name}!"

print(greet("AI Developer"))

💡 Use Case: Functions allow AI engineers to write once and reuse code for data transformations and model evaluation.


Function Arguments – Making AI Functions Flexible

2️⃣ Positional and Keyword Arguments

Functions can accept multiple arguments:

def train_model(epochs, learning_rate):
    print(f"Training for {epochs} epochs with learning rate {learning_rate}")

train_model(10, 0.01)  # Positional arguments
train_model(learning_rate=0.001, epochs=20)  # Keyword arguments

💡 Use Case: AI models often take configurable parameters like batch size and learning rate.


3️⃣ Default Argument Values

Providing default values makes functions more flexible:

def load_data(batch_size=32):
    print(f"Loading data with batch size {batch_size}")

load_data()  # Uses default value (32)
load_data(64)  # Overrides default value

💡 Use Case: Default parameters help set reasonable defaults while allowing customization in AI workflows.


Anonymous (Lambda) Functions – When Simplicity Matters

Lambda functions are one-line functions that don’t require def:

square = lambda x: x ** 2
print(square(4))  # Output: 16

💡 Use Case: Useful for quick data transformations in AI pipelines.

Example with map():

numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x ** 2, numbers))
print(squared)  # Output: [1, 4, 9, 16]

💡 Use Case: Lambda functions are commonly used in data preprocessing and augmentation.


Best Practices for AI Functions

Keep functions small and focused – Each function should do one thing well. ✅ Use meaningful namestrain_model() is clearer than func1(). ✅ Avoid global variables – Use arguments instead. ✅ Return values instead of printing – Makes functions reusable.


Conclusion

Functions improve modularity, readability, and reusability in AI code. By using arguments, default values, and lambda functions, Python allows for efficient, flexible AI development.

In the next chapter, we will explore how Python handles different data structures and their importance in AI workflows.