Project 3: Validate Orders
Lesson 45 of 48 in Coddy's Python for C# Developers course.
Challenge
BeginnerRetain the model and policies, and complete parse_order(line) to return an order or raise ValueError. Input now begins with nonnegative n followed by n comma-separated records: customer,quantity,unit_cents,policy. Strip field whitespace. Require exactly four fields, a nonempty customer, int-parsed quantity > 0, int-parsed price >= 0, and policy standard or bulk. Customer names contain no colon or comma. Numeric text is signed base-ten when valid; malformed fields may be arbitrary text. The count is always valid. Replace the previous single-order code in main() with batch input. Output ok:customer:total or invalid per record and continue. An empty batch prints nothing. Catch only expected validation failures.
C# transfer checkpoint
TryParse exposes success as a bool in C#; Python int raises ValueError on malformed text. Keep parsing separate from business validation.
C# reference excerpt: executable statements assume using System; type-only excerpts illustrate the declared contract.
if (!int.TryParse("bad", out int quantity))
Console.WriteLine("invalid");Python pattern
try:
quantity = int("bad")
except ValueError:
print("invalid")Editable implementation files: order.py, standard_policy.py, bulk_policy.py, functions.py, main.py. The locked driver.py is the supplied launcher or input/output harness and must remain unchanged.
Use the supplied input contract without prompts. Print only the required lines, each ending in a newline.
All four steps keep order.py, standard_policy.py, bulk_policy.py, functions.py, main.py, and driver.py. Order belongs in order.py; policy classes belong in their named files; make_policy and parse_order belong in functions.py; main.py owns input/output inside main(). Carry forward the previous editable files and implement this step's additions. Replace obsolete output inside main(); do not add a second entry point. The current locked driver calls main once, then checks APIs without more input or output.
Try it yourself
from order import Order
from standard_policy import StandardPolicy
from bulk_policy import BulkPolicy
from functions import make_policy, parse_order
from main import main
main()
assert StandardPolicy().total(1009) == 1009
assert BulkPolicy().total(999) == 999
assert BulkPolicy().total(1009) == 909
assert make_policy("standard").total(1200) == 1200
assert make_policy("bulk").total(1200) == 1080
class ProbePolicy:
def __init__(self):
self.calls = []
def total(self, subtotal):
self.calls.append(subtotal)
return subtotal + 17
probe_policy = ProbePolicy()
probe_order = Order("probe", 2, 11, probe_policy)
assert (probe_order.customer, probe_order.quantity, probe_order.unit_cents) == ("probe", 2, 11)
assert probe_order.subtotal() == 22 and probe_order.total() == 39
probe_order.quantity = 3
assert probe_order.total() == 50 and probe_policy.calls == [22, 33]
probe_order.policy = StandardPolicy()
assert probe_order.total() == 33
parsed = parse_order(" Probe , 2 , 505 , bulk ")
assert isinstance(parsed, Order)
assert (parsed.customer, parsed.quantity, parsed.unit_cents) == ("Probe", 2, 505)
assert parsed.subtotal() == 1010 and parsed.total() == 909
for invalid_line in ["broken", "A,1,2,standard,extra", ",1,2,bulk", "A,0,1,standard", "A,1,-1,bulk", "A,no,2,standard", "A,1,2,vip"]:
try:
parse_order(invalid_line)
except ValueError:
pass
else:
raise AssertionError("parse_order must reject invalid records")
All lessons in Python for C# Developers
1C# Foundations in Python
Run the Python WorkspaceOutput, Strings, and CommentsTyped Locals to Python NamesDivision and RemaindersIndentation Instead of BracesRecap: Port a Receipt4Loops and Transformations
From foreach to forIndexes and Dictionary ItemsSentinels and Loop ControlFrom LINQ to ComprehensionsRecap: Stable Ranking2None and Decisions
Nullable Values and NoneEquality, Identity, and TypesTruth Tests and FallbacksBranch PriorityRecap: Eligibility Rules3Collections and References
From List<T> to listTuples and UnpackingDictionary Keys and ValuesSets, Aliases, and CopiesRecap: Stock Lookup6Reliable Python Programs
Input and Exact OutputExceptions and ValidationImports and the Main GuardType Hints and Runtime TypesRecap: Validate a Batch9Project: Order Processor
Project 1: Order ModelProject 2: Pricing PoliciesPractice on your own: Online Python compiler