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…
- CourseData analytics zero to hero
- Lesson3 of 30
- Video11 min
- FormatJupyter notebook · 9 code cells
What you'll learn
Data
No separate download needed — the notebook creates or downloads everything it uses.
📓 Full notebook
Download .ipynbData 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()
def greet_person(name):
print(f'Hello, {name}!')
greet_person('Sam')
greet_person('Priya')
Return Values#
def add_tax(price, tax_rate):
return price * (1 + tax_rate)
total = add_tax(50, 0.08)
print(total)
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))
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}')
Part 4: Importing Modules#
import math
print(math.sqrt(64))
print(math.pi)
print(math.ceil(4.2))
print(math.floor(4.8))
import random
print(random.randint(1, 100))
print(random.choice(['A', 'B', 'C', 'D']))
from datetime import date
today = date.today()
print(today)
print(today.year)
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))
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.
What does
add_tax(100)return?def add_tax(price, tax_rate=0.08): return price * (1 + tax_rate)
tax_rate has a default of 0.08, so it can be skipped. 100 * 1.08 = 108.0.
What is the main difference between
print()inside a function andreturn?return hands a value back so you can use it later (e.g.
total = add_tax(50)). print just displays text.What does
math.ceil(4.2)give?ceil rounds up to the next whole number, so 4.2 becomes 5. floor would 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])
A function can return several values as a tuple, and you can unpack them into separate variables.
Which line imports only the
dateclass from thedatetimemodule?The syntax is
from module import name, sofrom datetime import date.
💻 Practice exercises
Try each one in the notebook or in your own editor before opening the solution.
Write a function
greet_person(name)that printsHello, <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')
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))
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.



