4. Recording sales and the report¶
Lines 50–63
The last two methods of the class deal with sales. sell lowers a product's stock and records the sale; report adds up every recorded sale to give the total quantity sold and the total revenue.
Code for this part¶
50 def sell(self, name, qty):51 if name not in self.products:52 raise ValueError('کالا پیدا نشد')53 if qty <= 0:54 raise ValueError('تعداد باید مثبت باشد')55 product = self.products[name]56 if qty > product['qty']:57 raise ValueError('موجودی کافی نیست')58 product['qty'] -= qty59 self.sales.append({'name': name, 'qty': qty, 'total': qty * product['sell']})60 self.save()61 62 def report(self):63 return sum(s['qty'] for s in self.sales), sum(s['total'] for s in self.sales)
Click a line number to jump to its explanation; click “line …” in an explanation to highlight that line in the code.
Line by line¶
- line 50
def sell(self, name, qty):¶ selltakes a product name and a quantity. It is called from the module-level functionsell(line 103).- line 53
if qty <= 0:¶ - The quantity must be greater than zero. Unlike line 31, zero is rejected too, since selling nothing makes no sense.
- line 55
product = self.products[name]¶ - Stores the product's dictionary in
product. This is not a copy but a reference to the same dictionary insideself.products, so any change toproductchanges the original data. - line 58
product['qty'] -= qty¶ -=means “subtract from itself”: the stock goes down by the quantity sold. Becauseproductis a reference (line 55),self.productschanges too.- line 59
self.sales.append({'name': name, 'qty': qty, 'total': qty * product['sell']})¶ - Appends a sale record to the list.
totaluses the sale price at this moment, so editing the price later (line 41) does not change the totals of past sales.
Note
Example: if sales holds {'qty': 2, 'total': 30} and {'qty': 5, 'total': 100}, report() returns (7, 130).
How it connects to the rest of the code¶
See also
Shop.sell- The “record sale” button: function
sellline 102 →shop.sell(name, quantity)line 103. Shop.report- The “sales report” button: function
reportline 109 → line 110, which unpacks the tuple intocountandincomeand shows them on line 111. self.sales- Created in the constructor line 11 and filled from the file in
loadline 24. product['qty']- The reduced stock is shown in the table again by
refreshon line 87 (line 118).
Check your understanding¶
Try to answer each question before opening it.
Why does
product['qty'] -= qtyon line 58 also changeself.products?Show answer
producton line 55 is a reference to the same dictionary, not a copy.Selling 0 items fails, but a price of 0 is accepted. Which lines decide this?
What does
report()return when there are no sales yet?Show answer
(0, 0), becausesumof an empty sequence is 0.If a price is edited after a sale, does that sale's
totalchange?Show answer
No. line 59 stores the total at the moment of the sale.