runtime
275 / 500
question 275 Data Models & Typing · medium

A price and a discount that guard themselves

Write Product(sku, price, discount_percent=0) whose rules hold after every change, not just at creation. price is a property whose setter converts to float, rounds to 2 places and refuses negatives. discount_percent is a property whose setter accepts only whole numbers from 0 to 90. sale_price is a read-only property: the price after the discount, rounded to 2 places.

`price`setter: round(float(value), 2); below 0 → ValueError
`discount_percent`setter: an int from 0 to 90 (bool doesn't count as an int here) → otherwise ValueError
`sale_price`read-only: price × (100 − discount_percent) / 100, rounded to 2 places
`__init__`assigns through the properties, so the same rules apply at creation

Loading your progress…

A price and a discount that guard themselves — Python practice · Runtime