Bird
0
0

Identify the error in this Order class method that calculates total cost:

medium📝 Analysis Q14 of 15
LLD - Design — Online Shopping Cart
Identify the error in this Order class method that calculates total cost:
class Order:
def __init__(self, cart):
self.cart = cart
self.total = 0
def calculate_total(self):
for product, qty in self.cart.items():
self.total += product.price * qty
return self.total
AReturning total instead of printing it
BUsing self.cart.items() instead of self.cart.products.items()
CMultiplying price by quantity incorrectly
DNot resetting self.total before calculation
Step-by-Step Solution
Solution:
  1. Step 1: Analyze total calculation logic

    The method adds product price times quantity to self.total in a loop.
  2. Step 2: Check for accumulation errors

    Since self.total is not reset before calculation, repeated calls will add to previous total, causing incorrect sums.
  3. Final Answer:

    Not resetting self.total before calculation -> Option D
  4. Quick Check:

    Reset total before sum to avoid accumulation [OK]
Quick Trick: Reset totals before summing to avoid repeated addition errors [OK]
Common Mistakes:
  • Assuming cart.items() is invalid without context
  • Thinking multiplication is wrong when it is correct
  • Confusing return with print for output

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes