Home > Back-end >  How to calculate total price with discount by the products in Python
How to calculate total price with discount by the products in Python

Time:10-24

I created two classes. In class Cart i need to implement the method get_total_price that calculate total price with discount. Discount depends on count product:

count        discount
at least 5     5%
at least 7     10%
at least 10    20%
at least 20    30%
more than 20   50%
class Product:
    
    def __init__(self, name, price, count):
        self.name = name
        self.price = price
        self.count = count


class Cart:
    
    def __init__(self, *products_list):
        self.products_list = products_list
    
    def get_total_price(self):
        pass

        
products = (Product('p1',10,4),
Product('p2',100,5),
Product('p3',200,6),
Product('p4',300,7),
Product('p5',400,9),
Product('p6',500,10),
Product('p7',1000,20))
cart = Cart(products)
print(cart.get_total_price())
The result of running the program should be 24785.0

Can someone help, because I can not figure out how to get the attributes(price, count) to calculate the discount.

CodePudding user response:

It seems cart.products_list returns a tuple containing the products list (so, a tuple in another tuple). If it's not intended, remove the '*'.

Here is a working solution for the current structure; if you remove '*', remove [0] in the get_total_price method.

def discount_mult(q):
        if q > 20:
            return .5
        elif q >= 20:
            return .7
        elif q >= 10:
            return .8
        elif q >= 7:
            return .9
        elif q >= 5:
            return .95
        else:
            return 1    

class Product:    
    def __init__(self, name, price, count):
        self.name = name
        self.price = price
        self.count =  count    

class Cart:        
    def __init__(self, *products_list):
        self.products_list = products_list
    
    def get_total_price(self):
        return sum([i.price*i.count*discount_mult(i.count) for i in self.products_list[0]])

        
products = (Product('p1',10,4),Product('p2',100,5),Product('p3',200,6),Product('p4',300,7),
            Product('p5',400,9),Product('p6',500,10),Product('p7',1000,20))
cart = Cart(products)
print(cart.get_total_price())
  • Related