Python Functions Practice: Bonus Calculator, Product Pipeline and a Math Package
Three work-style use cases (an HR bonus calculator, a product discount pipeline, and a mathkit package) turned into requirement lists and prompts, with one possible result for each read against the list, including the empty-input crash the list forgot.
What you will learn
- Turn a use case into a requirements list and put it in a Role, Context, Task, Format prompt
- Read a **kwargs function with a default, a filter/map pipeline and its comprehension version
- Build a small package (mathkit) with stats and geometry modules and import it
- Check output against the same list, and find gaps like an unhandled empty input
Before you start
- Python Functions: Parameters, Return, Scope, *args and **kwargs
- Python lambda, map, filter, Modules and Packages
- Python Comprehensions
Think about a shopping list. You write down what you need: milk, eggs and bread. Someone else takes it to the shop, and how they get around the shop is up to them. When they come back, you don't just trust the bags. You tick them off against the same list, and if the bread's missing, you see it right away.
Your requirements are that list. Use them once to write the prompt, and once more to check the result. Here are three use cases, each built with the functions you know.
Use case 1: an employee bonus calculator
The HR team needs a program that works out bonuses. As a list:
- A variable number of employees: three today, maybe thirty tomorrow.
- A bonus percent that can change per run, defaulting to 10%.
- Each name and amount in a neat table.
- The total payout at the end.
Now the hints: what you already know that fits each line. Any number of name and salary pairs is **employees. A percent with a default is bonus_pct=0.10. Each row is a loop over employees.items(). The table is an f-string with widths, and the total is a running total or a sum. Hints can go into the prompt, because the more you say, the less the tool has to guess.
A weak prompt says "write a bonus program". A better one, with the four parts from prompting fundamentals:
Act as a Python tutor. An HR team pays bonuses, and I'm learning functions. Write a function that takes any number of name and salary pairs, a bonus percent that defaults to 10%, prints an aligned table of name, salary and bonus, and prints the total payout. Use type hints. One Python file, called twice: once with the default and once with 15%.
One possible result. Your tool's answer will look different, and that's fine:
def calculate_bonuses(
bonus_pct: float = 0.10, **employees: float
) -> float:
total = sum(
pay * bonus_pct for pay in employees.values()
)
print(f"== BONUS REPORT ({bonus_pct:.0%}) ==")
for name, salary in employees.items():
bonus = salary * bonus_pct
print(
f"{name:<8}| ${salary:>8,} | ${bonus:>7,.0f}"
)
print("-" * 30)
print(f"Total payout: ${total:,.0f}")
return total
calculate_bonuses(Asha=52000, Ben=61000, Chen=48500)
print()
calculate_bonuses(0.15, Asha=52000, Ben=61000)
== BONUS REPORT (10%) ==
Asha | $ 52,000 | $ 5,200
Ben | $ 61,000 | $ 6,100
Chen | $ 48,500 | $ 4,850
------------------------------
Total payout: $16,150
== BONUS REPORT (15%) ==
Asha | $ 52,000 | $ 7,800
Ben | $ 61,000 | $ 9,150
------------------------------
Total payout: $16,950
**employees collects every name and salary. The total uses a generator expression inside sum; the hint said a running total or a sum, and either is correct. {name:<8} pads the name to eight characters and , puts commas in the money, so the columns line up.
Read it against the list. The first call passes no percent and the heading says 10%: the default worked. Asha's 52,000 gives 5,200 and the columns line up. 16,150 is the three bonuses added up. The second call passes 0.15 and only two people: variable count and custom percent both work. All those ticks came from reading the output, not from trusting the code.
Use case 2: a product data pipeline
An analytics team has a raw list of product dictionaries. The list: remove anything out of stock, apply a discount to premium products, print a clean summary. The hints: each product is a dict with name, price and stock; out of stock is a filter with stock > 0; premium is another filter with price > 100; the discount is a map that makes a new dict, so the original stays as it was.
Act as a Python tutor. An analytics team has a list of product dictionaries with name, price and stock. Keep products with stock above 0, keep those with price above 100, give them 15% off as a new key, and print the names at the end. One file, with a labelled report. Add a comment explaining each statement.
That last line is useful when you're not sure how the code works: it fills the answer with explanations so you can follow the logic. One possible result (comments left out here):
products = [
{"name": "Laptop", "price": 999, "stock": 5},
{"name": "Mouse", "price": 29, "stock": 50},
{"name": "Monitor", "price": 349, "stock": 3},
{"name": "Webcam", "price": 89, "stock": 0},
{"name": "Keyboard", "price": 75, "stock": 12},
]
in_stock = list(filter(
lambda p: p["stock"] > 0, products
))
premium = list(filter(
lambda p: p["price"] > 100, in_stock
))
discounted = list(map(
lambda p: {**p, "disc_price": p["price"] * 0.85},
premium,
))
names = list(map(lambda p: p["name"], discounted))
print("=== DISCOUNT REPORT (15% off) ===")
for p in discounted:
saving = p["price"] - p["disc_price"]
print(
f"{p['name']:<8} ${p['price']:>4} -> "
f"${p['disc_price']:>7.2f} (save ${saving:.2f})"
)
print(f"Names: {names}")
=== DISCOUNT REPORT (15% off) ===
Laptop $ 999 -> $ 849.15 (save $149.85)
Monitor $ 349 -> $ 296.65 (save $52.35)
Names: ['Laptop', 'Monitor']
Watch five products go through. The first filter drops the Webcam (stock 0), leaving four. The second drops the Mouse at 29 and the Keyboard at 75. The map copies each dict with {**p, ...} and adds a discount price. Each step feeds the next.
A question the output raises
Webcam is gone: tick. Laptop saves 149.85, which is 15% of 999: tick. Monitor saves 52.35: tick. But the Mouse and Keyboard are in stock, and they aren't in the report. Did you want that? The request says to discount premium products, but not whether the summary shows the rest. The code did what the prompt said. If your team wants every product listed, that's one more line in the task. Reading the output is how you find gaps like this.
Same pipeline, comprehension style
Add one line to the prompt, "use comprehensions instead of map and filter", and you might get:
discounted = [
{**p, "disc_price": p["price"] * 0.85}
for p in products
if p["stock"] > 0 and p["price"] > 100
]
names = [p["name"] for p in discounted]
With the same products (now hinted as list[dict]) and the same report loop, the output is identical, line for line. The prompt decides the style; your list decides whether it's correct. (See Python comprehensions.)
Use case 3: a custom math toolkit package
A developer wants reusable math functions, organised as a proper package. The list:
mathkit/
__init__.py empty
stats.py mean, median, mode, any count of numbers
geometry.py circle_area, rect_area
main.py imports both and calls every function
Why list files and folders at all? If you just say "write the code", the tool focuses on the output and may take the shortest way there, which may not fit your project's structure. So the structure goes into the prompt; you can even draw the tree as plain text. The prompt also pins small details: *nums for stats, 3.14159 for pi, from mathkit import stats, geometry in main, standard library only, each file shown separately.
# mathkit/stats.py
def mean(*nums: float) -> float:
return sum(nums) / len(nums)
def median(*nums: float) -> float:
s = sorted(nums)
mid = len(s) // 2
if len(s) % 2:
return s[mid]
return (s[mid - 1] + s[mid]) / 2
def mode(*nums: float) -> float:
return max(nums, key=nums.count)
# mathkit/geometry.py
PI = 3.14159
def circle_area(radius: float) -> float:
return PI * radius ** 2
def rect_area(width: float, height: float) -> float:
return width * height
# main.py
from mathkit import stats, geometry
print("=== STATS RESULTS ===")
print(f"Mean: {stats.mean(4, 6, 7, 8, 10)}")
print(f"Median: {stats.median(4, 6, 7, 8, 10)}")
print(f"Median: {stats.median(4, 6, 8, 10)}")
print(f"Mode: {stats.mode(4, 4, 6, 7, 8)}")
print("\n=== GEOMETRY RESULTS ===")
print(f"Circle (r=5): {geometry.circle_area(5):.2f}")
print(f"Rectangle 4x6: {geometry.rect_area(4, 6)}")
=== STATS RESULTS ===
Mean: 7.0
Median: 7
Median: 7.0
Mode: 4
=== GEOMETRY RESULTS ===
Circle (r=5): 78.54
Rectangle 4x6: 24
4, 6, 7, 8 and 10 add to 35, divided by 5 is 7.0. With five numbers the median is the middle one, 7; with four there's no single middle, so it averages 6 and 8. mode uses max with a key: for each number, how often it appears. 4 appears twice, so 4 wins. The folder, the modules and every call are there. Notice main.py only says which function it wants; the how stays inside the package.
What the list forgot
from mathkit import stats
print(stats.mean())
Traceback (most recent call last):
File "S02L03_Practice\empty_data.py", line 3, in <module>
print(stats.mean())
~~~~~~~~~~^^
File "S02L03_Practice\mathkit\stats.py", line 2, in mean
return sum(nums) / len(nums)
~~~~~~~~~~^~~~~~~~~~~
ZeroDivisionError: division by zero
With no numbers, *nums is empty, so it's 0 divided by 0. The prompt never said what should happen with no numbers, so the tool had nothing to go on. That's one more line for your list: say what happens with empty input, prompt again, and read the result again.
Quick recap
| Use case | Functions you read | What reading the output found |
|---|---|---|
| Bonus calculator | **kwargs, a default, sum with a generator | every requirement met |
| Product pipeline | filter, map, lambda, then a comprehension | a gap: non-premium products are left out |
| mathkit package | *args, modules, from package import | a crash: empty input was never specified |
Try it yourself
Pick one of the three use cases and write the prompt yourself, without copying these. Run what you get, and read it against the list.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Python Functions: Parameters, Return, Scope (LEGB), *args and **kwargs
A function is a recipe: write it once, hand in ingredients, get a dish back. input and import, def and return, defaults, returning a tuple, functions as objects, the LEGB scope rule, global and nonlocal, then *args and **kwargs, with real output.
Type Hints on Python Functions: Parameters, Returns, None and Collections
A type hint is a label on a jar: it says what belongs inside but stops nothing. Hint parameters and returns, -> None, str | None, list[str] and dict[str, int], see add("2", "3") print 23, and read hints back with __annotations__.
Python lambda, map, filter, Modules and Packages (with pip and venv)
A lambda is a sticky note next to a def recipe card. Sort words and students with key, map as a conveyor belt, filter as a gate, then your own package with __init__.py, two import errors, and pip install into an activated .venv.
