Mathew K Analytics

Lesson 3 · Data analytics zero to hero

Python Functions & Modules for Reusable Code | Data Analytics #3

Packaging reusable logic into functions, and pulling in Python's built-in modules. Builds directly on videos one and two, variables and control flow. Let's…

What you'll learn

Data

No separate download needed — the notebook creates or downloads everything it uses.

📓 Full notebook

Download .ipynb

Data Analytics Zero to Hero, Video 3: Functions and Modules#

  • Video three of the 30-part series: packaging reusable logic into functions, and pulling in Python's built-in modules.
  • Builds directly on videos one and two, variables and control flow.
  • Let's jump straight in.

Before You Start#

  • Open a new Jupyter Notebook in VS Code and select your Python interpreter as the kernel.

Part 1: Defining and Calling Functions#

def greet():
    print('Hello, analyst!')

greet()
Hello, analyst!
def greet_person(name):
    print(f'Hello, {name}!')

greet_person('Sam')
greet_person('Priya')
Hello, Sam!
Hello, Priya!

Return Values#

def add_tax(price, tax_rate):
    return price * (1 + tax_rate)

total = add_tax(50, 0.08)
print(total)
54.0

Part 2: Default and Keyword Arguments#

def add_tax(price, tax_rate=0.08):
    return price * (1 + tax_rate)

print(add_tax(100))
print(add_tax(100, 0.15))
print(add_tax(price=100, tax_rate=0.05))
108.0
114.99999999999999
105.0

Part 3: Multiple Return Values and Docstrings#

def price_stats(prices):
    """Return the minimum, maximum, and average of a list of prices."""
    lowest = min(prices)
    highest = max(prices)
    average = sum(prices) / len(prices)
    return lowest, highest, average

low, high, avg = price_stats([19.99, 45.50, 12.75, 88.00])
print(f'Low: {low}, High: {high}, Avg: {avg:.2f}')
Low: 12.75, High: 88.0, Avg: 41.56

Part 4: Importing Modules#

import math
print(math.sqrt(64))
print(math.pi)
print(math.ceil(4.2))
print(math.floor(4.8))
8.0
3.141592653589793
5
4
import random
print(random.randint(1, 100))
print(random.choice(['A', 'B', 'C', 'D']))
22
C
from datetime import date
today = date.today()
print(today)
print(today.year)
2026-08-16
2026

Part 5: Mini Project A Reusable Discount Calculator#

import math

def apply_discount(price, discount_pct=10, round_up=False):
    """Apply a percentage discount to a price, optionally rounding the result up."""
    discounted = price * (1 - discount_pct / 100)
    if round_up:
        return math.ceil(discounted)
    return round(discounted, 2)

print(apply_discount(59.99))
print(apply_discount(59.99, discount_pct=25))
print(apply_discount(59.99, discount_pct=25, round_up=True))
53.99
44.99
45

Wrap-Up: What You Learned#

  • Defining and calling functions, with parameters and return values.
  • Default arguments, keyword arguments, and returning multiple values at once.
  • Docstrings for documenting what a function does.
  • Importing built-in modules like math, random, and datetime.
  • A small reusable tool combining all of it into one function.
  • Functions are how you'll organize every real analysis from here on. Video four covers Python's core data structures lists, dicts, tuples, and sets the containers you'll store real data in. Subscribe so it lands automatically.

🧠 Test yourself

Pick an answer to check it. Your best score is saved in this browser.

  1. What does add_tax(100) return?

    def add_tax(price, tax_rate=0.08):
        return price * (1 + tax_rate)
    
  2. What is the main difference between print() inside a function and return?

  3. What does math.ceil(4.2) give?

  4. What does this code do?

    def price_stats(prices):
        return min(prices), max(prices), sum(prices) / len(prices)
    
    low, high, avg = price_stats([10, 20, 30])
    
  5. Which line imports only the date class from the datetime module?

💻 Practice exercises

Try each one in the notebook or in your own editor before opening the solution.

  1. Write a function greet_person(name) that prints Hello, <name>!. Call it for 'Sam' and 'Priya'.

    💡 Hint

    Use def, one parameter, and an f-string.

    ✅ Show solution
    def greet_person(name):
        print(f'Hello, {name}!')
    
    greet_person('Sam')
    greet_person('Priya')
    
  2. Write add_tax(price, tax_rate=0.08) that returns the price including tax. Call it with just a price, with a custom rate positionally, and with keyword arguments, and print each result.

    💡 Hint

    Return price * (1 + tax_rate).

    ✅ Show solution
    def add_tax(price, tax_rate=0.08):
        return price * (1 + tax_rate)
    
    print(add_tax(100))
    print(add_tax(100, 0.15))
    print(add_tax(price=100, tax_rate=0.05))
    
  3. Write apply_discount(price, discount_pct=10, round_up=False) with a docstring. It returns the discounted price rounded to 2 decimals, or rounded up to a whole number with math.ceil if round_up is True. Test with 59.99.

    💡 Hint

    Compute price * (1 - discount_pct / 100) first, then use an if for round_up.

    ✅ Show solution
    import math
    
    def apply_discount(price, discount_pct=10, round_up=False):
        """Apply a percentage discount, optionally rounding up."""
        discounted = price * (1 - discount_pct / 100)
        if round_up:
            return math.ceil(discounted)
        return round(discounted, 2)
    
    print(apply_discount(59.99))
    print(apply_discount(59.99, discount_pct=25))
    print(apply_discount(59.99, discount_pct=25, round_up=True))
    

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.