LEARN BY BUILDING
Python Basics: Validate and Total Service Items
Python is useful for server logic, data processing and automations. Begin with a small function that has clear inputs and returns a value. The example totals service items using decimal arithmetic and explicit validation, so its behaviour can be checked before a web interface is added.
STEP 1
Run the program locally
Save the example as quote.py and run python3 quote.py in your terminal. It uses only the Python standard library and should print 62.50. Pass prices and quantities as decimal strings. This avoids converting an already rounded binary floating-point value into a decimal value.
- Change the quantity from 2.5 to 3 and expect 75.00.
- Pass an empty list and check the error.
- Try a negative or non-finite value and check that it is rejected.
STEP 2
Understand the validation boundary
The function checks numeric values before multiplying them. It rounds each line to cents using the stated rounding mode and then sums the lines. That is one explicit policy; a real invoicing workflow may require a different policy. Keep those requirements separate from presentation.
- Use representative business examples to choose a rounding policy.
- Validate required fields before calling calculation code.
- Keep secrets and private records out of printed diagnostics.
STEP 3
Connect it to a Django workflow
A Django view can accept a request, validate it with a form and call a pure calculation function. Save authoritative business records on the server and check the user’s permissions. A management command or background worker can reuse the same function without duplicating the logic in a template.
- Keep database changes separate from formatting.
- Test business logic before adding API calls.
- Add timeouts and duplicate handling when external systems are involved.
Complete runnable example
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
def total(items):
if not items:
raise ValueError("Add at least one item")
result = Decimal("0.00")
for item in items:
try:
quantity = Decimal(item["quantity"])
price = Decimal(item["price"])
except (InvalidOperation, KeyError, TypeError, ValueError) as exc:
raise ValueError("Use decimal strings for quantity and price") from exc
if not quantity.is_finite() or not price.is_finite():
raise ValueError("Values must be finite")
if not 0 < quantity <= 1000000 or not 0 <= price <= 1000000:
raise ValueError("Values are outside the supported range")
result += (quantity * price).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
return result
if __name__ == "__main__":
print(total([{"quantity": "2.5", "price": "25.00"}]))Use AI with a clear specification
Adapt the bracketed details to your project. Ask your coding assistant to explain its changes, then run the examples and checks yourself.
Review this Python calculation for validation, decimal arithmetic and explicit rounding. Add tests for expected totals, missing keys, negative numbers and non-finite values. Explain how a Django form could validate request data before calling the function.
BUILD IT WITH HOW2CODE
Need this adapted to your business?
Tell us about your workflow, existing tools and expected result. We’ll review the brief and discuss the scope with you.
Discuss this project →