Hello! Welcome to the next lesson in our Python fundamentals module.
In our last session, we explored Python's core data structures: lists, dictionaries, tuples, and sets. We ended with a thought: if you need to perform the same analysis—like calculating an average—on multiple sets of data, you'd have to copy and paste your code. This is not only tedious but also a major source of errors.
Today, we solve that problem. This lesson introduces one of the most powerful concepts in programming: functions. Think of functions as named, reusable blocks of code that perform a specific task. For a Business Analyst, mastering functions is the key to moving from simple, one-off scripts to writing robust, scalable, and professional-grade analytical tools.
Our learning outcome is to define and call functions with parameters and return values to create reusable code. We'll cover:
- The fundamental reasons for using functions (the DRY principle).
- The syntax for defining and calling your own functions.
- How to pass information into functions using parameters.
- How to get results back from functions using the return statement.
- The importance of documenting functions with docstrings, a key professional practice.
1. Why Use Functions? The "Don't Repeat Yourself" Principle
Imagine you are analyzing sales data and you repeatedly need to check if a list of numbers is all even. Without functions, you might copy and paste your logic every time a new list arrives.
This is where functions become essential. They help you adhere to the DRY (Don't Repeat Yourself) principle, a cornerstone of good software development.
Python Functions for Data Science / Data Analysis - P.5
To see this in action, watch the beginning of the video 'Python Functions for Data Science / Data Analysis' by Luke Barousse. He provides a perfect example of how repeating code leads to errors and how a function solves the problem elegantly.
Watch from the beginning to 4:39. Notice the mistake he makes when copying and pasting the code, a very common real-world scenario.
As the video shows, functions are not just about saving typing. The benefits are much deeper, especially for an analyst:
- Reduces Errors: You fix a bug or make an improvement in one place, and it's corrected everywhere the function is used.
- Improves Readability: Giving a block of code a descriptive name (e.g.,
calculate_click_through_rate) makes your script read more like plain English. - Frees Up Mental Capacity: Once you've written and tested a function, you can trust it to do its job without needing to remember the low-level details of its implementation. This allows you to focus on the bigger analytical picture.
2. The Anatomy of a Python Function
A function has a clear structure: a definition, a body, and an optional return value.

Let's break down these pieces.
Defining and Calling a Basic Function
You define a function using the def keyword, followed by the function's name, parentheses (), and a colon :. The code that belongs to the function is indented beneath the definition.
Python Functions | Python Tutorial for Absolute Beginners #1
For a clear, concise explanation of the basic syntax, watch this segment from 'Python Functions' by Programming with Mosh.
Watch from 0:34 to 2:34. This covers the def keyword, naming conventions, indentation, and how to call the function you've created.
Passing Information with Parameters and Arguments
Most functions need inputs to work on. These are defined as parameters in the function definition. When you call the function, you provide actual values for these parameters, which are called arguments.
Understanding Functions, Parameters, Arguments & Return Values in Python
The terms 'parameter' and 'argument' are often used interchangeably, but there's a clear distinction. This article, 'Understanding Functions, Parameters, Arguments & Return Values in Python', explains it well.
Read the section titled 'Parameters vs Arguments'. The analogy of parameters as 'empty boxes' and arguments as the 'actual values' you put in them is very helpful.
Here is a simple example:
# 'name' is the parameter
def greet_user(name):
print(f"Hello, {name}! Welcome to the analytics dashboard.")
# 'Alice' is the argument
greet_user('Alice')
# 'Bob' is the argument
greet_user('Bob')
Getting a Result Back with return
Some functions just perform an action, like our greet_user function which prints a message. However, more often than not, you want a function to calculate a value and give it back to you. This is done with the return statement.

Python Functions | Python Tutorial for Absolute Beginners #1
Distinguishing between functions that perform a task and functions that return a value is crucial. Let's watch another clip from Programming with Mosh that clarifies this.
Watch from 4:43 to 7:20. Pay close attention to why a function that returns a value is more reusable than one that is locked into printing to the terminal.
A function that uses return is far more powerful because you can store its output in a variable and use it in subsequent calculations. If a function doesn't have an explicit return statement, it implicitly returns a special value called None.
3. Practical Application: An AdTech Example
Let's apply these concepts to a common scenario from your AdTech background: calculating Conversion Rate (CVR).
Conversion Rate is a key metric defined as:
Let's create a reusable function for this.
def calculate_cvr(conversions, clicks):
"""Calculates the conversion rate from conversions and clicks."""
# To avoid a division by zero error, we check if clicks is zero.
if clicks == 0:
return 0.0 # Return 0.0 if there are no clicks.
cvr = (conversions / clicks) * 100
return cvr
# --- Let's use our function ---
# Campaign A data
campaign_a_clicks = 1500
campaign_a_conversions = 75
cvr_a = calculate_cvr(campaign_a_conversions, campaign_a_clicks)
# Campaign B data
campaign_b_clicks = 2300
campaign_b_conversions = 120
cvr_b = calculate_cvr(campaign_b_conversions, campaign_b_clicks)
print(f"Campaign A Conversion Rate: {cvr_a:.2f}%")
print(f"Campaign B Conversion Rate: {cvr_b:.2f}%")
# What if a new campaign has no clicks yet?
cvr_c = calculate_cvr(0, 0)
print(f"New Campaign Conversion Rate: {cvr_c:.2f}%")
Notice how clean this is. The logic for calculating CVR is defined once. We can now call it as many times as we need with different arguments, and the result is returned for us to use. The check for clicks == 0 is an example of building robust logic into your function.
Test your understanding!
Another key AdTech metric is Return on Ad Spend (ROAS), calculated as Revenue / Ad Spend.
Write a Python function called calculate_roas that takes two parameters, revenue and ad_spend, and returns the calculated ROAS. Then, call your function with $5000 in revenue and $1250 in ad spend and print the result.
Show answer
def calculate_roas(revenue, ad_spend):
"""Calculates the Return on Ad Spend."""
if ad_spend == 0:
return 0.0
roas = revenue / ad_spend
return roas
# Call the function with the given data
revenue_generated = 5000
spend_on_ads = 1250
my_roas = calculate_roas(revenue_generated, spend_on_ads)
print(f"The ROAS is: {my_roas}")
# Expected output: The ROAS is: 4.0
4. Writing Professional, Reusable Code
As a BA preparing formal documentation like BRDs and FSDs, you know the value of clarity and precision. The same applies to your code. Writing good functions is your first step toward creating professional, well-documented analytical assets.
Documenting with Docstrings
A docstring is a string literal that occurs as the first statement in a function definition. It explains what the function does, its parameters, and what it returns. This is crucial for making your code understandable to others (and to your future self!).
Writing Functions in Python— A Beginner's Guide
The article 'Writing Functions in Python— A Beginner's Guide' has an excellent section on why docstrings are so important for creating usable code.
Please read section 7, 'Add a docstring'. Notice how the docstring provides built-in instructions for the function's user. In professional environments, code without documentation is often considered incomplete.
In our calculate_cvr function above, this was the docstring:
"""Calculates the conversion rate from conversions and clicks."""
A more complete docstring follows a standard format:
def calculate_cvr(conversions, clicks):
"""Calculates the conversion rate from a number of conversions and clicks.
Args:
conversions (int): The total number of conversions.
clicks (int): The total number of clicks.
Returns:
float: The conversion rate as a percentage. Returns 0.0 if clicks is 0.
"""
# ... function body ...
A Complete Walkthrough: Building a Function for Analysis
Let's see how all these pieces come together in a more complex analytical task. This is the "learning by doing" part where you see a function built from the ground up to solve a real problem.
Python Functions for Data Science / Data Analysis - P.5
Let's return to Luke Barousse's video. He provides a fantastic step-by-step guide to building a function that reads a file and counts the number of lines spoken by a specific actor from 'The Office' TV show. This is a great proxy for a real-world BA task, like parsing log files or customer feedback.
Watch the segment from 18:18 to 28:05. Don't worry about memorizing every line of code. Instead, focus on the process: He clearly defines the task and the approach. He starts with a basic script that opens the file. He wraps that logic in a function. He adds a parameter (actor) to make it flexible. He adds logic to count the actor's lines and return the final count. Finally, he uses this function inside a loop to analyze multiple actors.
This walkthrough is a perfect model for how you should approach your own analytical tasks: start with a working piece of code, then encapsulate it in a flexible, reusable function.
Conclusion
Excellent work today! You have just learned the single most important technique for organizing and scaling your Python code. By packaging logic into functions, you make your scripts more reliable, readable, and powerful.
Key Takeaways:
- Functions are reusable blocks of code that help you follow the DRY (Don't Repeat Yourself) principle.
- You define them with
def function_name(parameter1, parameter2):. - Parameters are the placeholders for inputs in the function definition.
- Arguments are the actual values you pass to the function when you call it.
- The
returnstatement sends a value back from the function, allowing you to use the result of its work. - Docstrings are essential for documenting your functions and are a hallmark of professional code.
Preview of the Next Lesson:
Now that we know how to create reusable tools, we'll turn our attention to a very common type of data that BAs work with: text. In the next lesson, we will focus on basic string manipulation and formatting. You'll learn how to clean up text data, extract information, and format strings into professional-looking reports—skills you'll use constantly when preparing data for analysis and presentation.