Start learning free

LESSON 652 OF 673 · OBJECT-ORIENTED PROGRAMMING - CHALLENGES

Product Price in Python: Properties That Guard Their Values

Practice O(1) Read the full explanation

Build a Product class for a shop. A product has a name, a price and a discount.

The price is in cents, and it can never go below 0. The discount is a percent from 0 to 100. The setters keep both rules.

Implement the class Product:

  • Product(name, price) creates a product. Its discount starts at 0.
  • price is a property. Reading it gives the price.
  • Setting price to a negative number changes nothing. The old price stays.
  • discount is a property too. Reading it gives the discount.
  • Setting discount below 0 makes it 0. Setting it above 100 makes it 100.
  • final_price() returns the price with the discount taken off. It rounds down to a whole cent.

Keep the price and the discount private by convention, in self._price and self._discount. Other code goes through the properties.

Each test case makes one product. Then it runs a list of operations on it, in order.

The output has one line per test case. It shows the name and a colon. Then it lists what each read gives, separated by spaces.

 

Example 1:

Input:
    p = Product("Pen", 250)
    p.price
    p.discount = 10
    p.final_price()
    p.price = -40
    p.price
Output: Pen: 250 225 250
Explanation: 10% of 250 cents is 25 cents, so the pen costs 225.
The price can't be -40, so it stays 250.

Example 2:

Input:
    p = Product("Lamp", 999)
    p.discount = 150
    p.discount
    p.final_price()
    p.discount = -20
    p.discount
Output: Lamp: 100 0 0
Explanation: 150 is above 100, so the discount becomes 100.
With 100% off, the lamp costs 0.
Then -20 is below 0, so the discount becomes 0.

Example 3:

Input:
    p = Product("Mug", 999)
    p.discount = 15
    p.final_price()
    p.price = 0
    p.final_price()
Output: Mug: 849 0
Explanation: 15% off 999 cents leaves 849.15 cents.
Rounded down, that is 849.
A price of 0 is allowed. It stays 0 after any discount.

 

Constraints:

  • The first price is a whole number from 0 to 10,000,000.
  • A new price is from -10,000,000 to 10,000,000.
  • A new discount is from -1,000 to 1,000.
  • A name is one word of letters.
  • 1 to 1,000 operations per test case.
  • Each test case reads at least one value.
STEP 1 OF 9
    Ctrl + Enter to check

    PYTHON · OBJECT-ORIENTED PROGRAMMING - CHALLENGES

    Product Price in Python, explained

    Problem overview

    The task is a Product class with a name, a price in cents and a discount percent. Two rules protect the data. The price can never go below 0, and the discount always stays between 0 and 100. Other code reaches the price and the discount through properties, so the class can enforce those rules every time a value is set.

    Take Product("Pen", 250). Its discount starts at 0. After p.discount = 10, final_price() returns 225, because 10% of 250 cents is 25 cents. Then p.price = -40 is refused, so reading p.price still gives 250. For Product("Lamp", 999), setting the discount to 150 stores 100, so the final price is 0; setting it to -20 afterwards stores 0.

    Approach: two different rules

    The two setters treat bad input differently, and the difference is the heart of the lesson.

    • A negative price is ignored: the old price stays.
    • A discount outside 0 to 100 is clamped to the nearest allowed value: below 0 becomes 0, above 100 becomes 100.

    Python's tool for this is the property. A method marked @property runs when code reads p.price, and a method marked @price.setter runs when code writes p.price = 5. The caller still writes plain attribute syntax, with no parentheses, while the class keeps the real value in self._price. The leading underscore is only a convention: it tells other programmers not to touch the field directly. Python does not enforce it.

    The name stays a plain public attribute because it has no rule to protect.

    Step by step

    1. In __init__, store name in self.name.
    2. Store price in self._price and start self._discount at 0.
    3. Write the price getter: it returns self._price. The @property line above it makes p.price call it.
    4. Write the price setter, decorated with @price.setter, taking the new price as value. Assign it only when it is 0 or more. When it is negative, do nothing.
    5. Write the discount getter the same way.
    6. In the discount setter, handle the low side first: if value is below 0, store 0.
    7. Add an elif for the high side: if value is above 100, store 100.
    8. Add an else that stores value. The values 0 and 100 themselves land here and are kept.
    9. Write final_price: multiply the price by the percent the buyer still pays, 100 - self._discount, then divide by 100 with //.

    The solution in Python

    class Product:
        def __init__(self, name, price):
            self.name = name
            self._price = price
            self._discount = 0
    
        @property
        def price(self):
            return self._price
    
        @price.setter
        def price(self, value):
            if value >= 0:
                self._price = value
    
        @property
        def discount(self):
            return self._discount
    
        @discount.setter
        def discount(self, value):
            if value < 0:
                self._discount = 0
            elif value > 100:
                self._discount = 100
            else:
                self._discount = value
    
        def final_price(self):
            return self._price * (100 - self._discount) // 100

    Why multiply first, then use //

    Prices are whole cents, so the answer must be a whole number rounded down. The order matters. For a price of 999 and a discount of 15, the product is 999 * 85, which is 84915, and 84915 // 100 is 849. In ordinary division, 999 * 0.85 is 849.15, and rounding down gives the same 849, but integer arithmetic keeps everything exact and never touches floating point. Dividing first (999 // 100 * 85) would throw away the cents before the discount is applied and give 765, which is wrong.

    // floors toward negative infinity. That never matters here, since the price and the factor are both 0 or more.

    Using the class

    p = Product("Pen", 250)
    print(p.price)
    p.discount = 10
    print(p.final_price())
    p.price = -40
    print(p.price)
    250
    225
    250
    p = Product("Lamp", 999)
    p.discount = 150
    print(p.discount, p.final_price())
    p.discount = -20
    print(p.discount)
    100 0
    0
    p = Product("Mug", 999)
    p.discount = 15
    print(p.final_price())
    p.price = 0
    print(p.final_price())
    849
    0

    Complexity

    Every getter, setter and final_price is a few comparisons and one multiplication, so each takes constant time, and a product uses constant space. The test cases only run up to a thousand operations on one product.

    Why properties and not plain fields

    With a plain field, p.price = -40 would store -40 and nothing could stop it. A property keeps the nice syntax and puts a method between the caller and the stored value. The same idea shows up whenever a value must obey a rule: the rule lives in one place, the setter, and every assignment goes through it, including the ones made by code you haven't written yet.

    The lesson's tests only read and write through the properties, so the class is free to change how it stores the values later. Callers would not notice.

    Edge cases and common mistakes

    • A price of 0 is allowed. The check is value >= 0, not value > 0. A free product stays 0 after any discount.
    • A discount of exactly 0 or 100 is kept. The branches use strict comparisons (< 0, > 100), so both limits fall into the else and are stored as given.
    • Calling a property like a method. After @property, p.price already gives the number. Writing p.price() raises TypeError: 'int' object is not callable.
    • Forgetting the setter decorator. A property without a setter cannot be assigned to; Python raises an AttributeError.
    • Writing to self.price inside the price setter. That calls the setter again and recurses without end. Store into self._price.
    • Clamping the price too. The price is ignored when negative, not set to 0.
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free