Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Python
  • Python for AI: The Five Tools You Actually Need
  • Thinking Like a Python Architect in an AI-First World
  • Your First Python Program: print, Comments, sep and end
  • Set Up PyCharm for Python: Install, First Project and First Run
  • Run a Python File and Read the Error: Tracebacks in Three Steps
  • Python Data Types, Variables and Strings: Indexing, Slicing and f-strings
  • Python Operators: Arithmetic, Comparison, Logical, Membership, Identity and Precedence
  • Python Conditionals and Loops: if/elif/else, for, while, break and continue
  • Looping Over Real Data in Python: Dicts, Lists of Dicts, enumerate and zip
  • Checking AI-Written Python Code: A Six-Step Habit That Finds Three Hidden Faults
  • Python Basics Practice: Report Card, Shopping Cart and Password Checker from a Prompt
  • Python Functions: Parameters, Return, Scope (LEGB), *args and **kwargs
  • Type Hints on Python Functions: Parameters, Returns, None and Collections
  • Python lambda, map, filter, Modules and Packages (with pip and venv)
  • Python Functions Practice: Bonus Calculator, Product Pipeline and a Math Package
  • Python Lists, Tuples, Sets and Dicts, Plus Type Hints on Variables
  • Python Comprehensions: List, Dict, Set and Generator Expressions, Read as Loops
  • Python Class Methods, Static Methods and Properties: What Each One Receives
  • Python Classes and Objects: __init__, self and PEP 8 Names
  • Python Inheritance and Polymorphism: super(), Overriding and Duck Typing
  • Python Multiple Inheritance, the MRO and Mixins
  • Python Encapsulation and Special Methods: Underscores, __str__, __add__ and __len__
  • Python Composition, Abstract Classes and Dataclasses
  • Python OOP Practice: Design a Bank, an Employee System and a Library
  • Set Up a Python AI Project with uv, VS Code and an API Key in .env
  • uv and pyproject.toml: Start, Add, Run and Rebuild a Python Project
  • Python try and except Basics: Catch an Error and Keep Going
  • Read and Write a File in Python: open, with, Modes and Encoding
  • Python Custom Exceptions and Advanced Error Handling: raise, raise from and the Call Stack
  • Python Logging and Debugging: Levels, Handlers, logger.exception and breakpoint()
  • Python File Modes, pathlib and Context Managers: x, r+, rb, Path and __enter__/__exit__
  • Python CSV, JSON and Large Files: csv, json, yield Pipelines, tomllib and pickle
  • Python Practice: Build a Log File Analyzer and a File Organizer
  • Python Project Structure for AI-Assisted Development: Packages, config.py and AGENTS.md
  • Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy
  • Testing Python Code with pytest: assert, parametrize, fixtures and pytest.raises
  • Async Python: async def, await, asyncio.gather and the Blocking Trap
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • Getting Started with Flask: Routes, Jinja2 Templates and WSGI in One Small App
  • Your First Flask App with uv: From an Empty Folder to a Page in Debug Mode
  • Flask Routes, Templates and url_for: Converters, Forms, Redirects and the Signed Session
  • Flask-SQLAlchemy Models and Flask-Migrate: From a Python Class to a Real Table
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a Flask Blog: The App Factory, Blueprints, the Instance Folder and CORS Done Right
  • How a Request and a Login Flow Through a Flask Blog: Flask-Login, CSRF and the Signed Session
  • Testing a Flask Blog with pytest: A Test App from the Factory, Fixtures and the Test Client
  1. Blog
  2. /
  3. Python
  4. /
  5. Functions

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Functions

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.

One requirements list is used twice: once to write the prompt and once to check the output; any gap found becomes a new line on the list Requirements list 1 write the prompt 2 check the output a gap becomes a new line
The same list writes the prompt and checks the result.

Use case 1: an employee bonus calculator

The HR team needs a program that works out bonuses. As a list:

  1. A variable number of employees: three today, maybe thirty tomorrow.
  2. A bonus percent that can change per run, defaulting to 10%.
  3. Each name and amount in a neat table.
  4. 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 caseFunctions you readWhat reading the output found
Bonus calculator**kwargs, a default, sum with a generatorevery requirement met
Product pipelinefilter, map, lambda, then a comprehensiona gap: non-premium products are left out
mathkit package*args, modules, from package importa 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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Python · 15 of 48

Previous
Python lambda, map, filter, Modules and Packages (with pip and venv)
Next post
Python Lists, Tuples, Sets and Dicts, Plus Type Hints on Variables

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.

On this page

  • Use case 1: an employee bonus calculator
  • Use case 2: a product data pipeline
  • A question the output raises
  • Same pipeline, comprehension style
  • Use case 3: a custom math toolkit package
  • What the list forgot
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.