Defining Functions in Python: The Core of AI Apps
Spaghetti code won't scale your AI application. By mastering Python functions, you encapsulate LLM API calls, data cleaning pipelines, and prompt formatting into clean, reusable modules.
Anatomy of a Python Function
A function is simply a named block of code. You declare it using the def keyword, followed by the function name, parentheses (), and a colon :. Every line of code indented beneath the colon belongs to that function.
This encapsulation is vital when building AI apps. Instead of writing the openai.ChatCompletion.create() boilerplate twenty times, you wrap it in a single ask_ai() function.
Passing Data: Parameters vs. Arguments
Functions are useless if they can't process different data. Parameters are the variables you declare in the function definition. Arguments are the actual values you pass in when you execute the function.
You can also assign default parameters (e.g., def clean_text(text, lower=True):). If the caller doesn't provide the lower argument, Python automatically assumes it is True.
Getting Data Back: The Return Keyword
If a function processes an AI prompt, you need that result back in your main program. The return keyword passes data back to the caller and immediately terminates the function execution.
- Single Return:
return response_text - Multiple Returns: Python allows you to return tuples easily:
return summary, token_count
View Architecture Tips+
Do One Thing Well. A single Python function should not fetch data from a database, clean it, AND send it to an LLM. Write three separate functions: fetch_data(), clean_data(), and generate_insight(). This makes your AI app infinitely easier to debug and test.
❓ Frequently Asked Questions (Functions in Python)
What is the `def` keyword in Python used for?
Direct Answer: The `def` keyword in Python is used to define or declare a new function.
It tells the Python interpreter that the following indented block of code is a reusable component. It must be followed by the function's name and parentheses.
def greet_user(): print("Hello!")What is the difference between a parameter and an argument?
Parameter: The variable listed inside the parentheses in the function definition. It acts as a placeholder.
Argument: The actual, concrete value that is passed to the function when it is called.
# 'name' is the parameter def say_hello(name): return "Hello " + name # "Alice" is the argument say_hello("Alice")What does the `return` statement do in a Python function?
The `return` statement immediately ends the execution of the function call and sends the specified result back to the caller. If no return statement is used, a Python function automatically returns `None`.
def add(a, b): return a + b print("This will never print because return exits the function.")