Thursday, August 22, 2024

Demonstration Coding: Python Coding Shopping Cart (Simple Problem Solving - 2)

Problem solving illustration.

    Hello, everyone! Good evening. Today, we'll tackle another coding problem. We'll delve into creating classes, inheritance, instances, dictionary looping, and more. This will test our foundational Python programming skills. Let’s get started!


Coding Prompt: 1

Create a class called Item that contains a dictionary of shopping items and their prices

- The class Item should not take any arguments when initialized.
- Inside the class, define a variable items representing of items database.
- Items are phone (price 1000), headphones (price 100).


Coding Prompt: 2

Create a class Cart that inherits from the Item class and represents a user's shopping cart

- Inside Cart, define an empty variable to store items that the user selects for purchase.
- Define a variable that keeps track of the total cost of the selected items.
- Use super() to initialize the parent class.

 

Coding Prompt: 3

Write a method adds() that takes argument of item selected by user.

- When you instantiate a Cart() object, it returns the total quantity of items selected by the user.


Coding Prompt: 4

Write a method total() that calculates the total price of all items in the user's cart.

- Return the total price as the result.


Coding Prompt: 5

Process the class like this:

print(cart.total()) # should be: 0
cart.adds('phone')
print(len(cart.userSelectedItems)) # Should be: 1
print(cart.total()) # Should be: 1000
cart.adds('headphones')
cart.adds('headphones')
print(len(cart.userSelectedItems)) # Should be 3
print(cart.total()) # Should be: 1200


Answer:


class Item:
'''Database of items.'''
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.items = {
'phone': 1000,
'headphones': 100
}

class Cart(Item):
'''User's shopping cart.'''
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.userSelectedItems: list[str] = []
self.totalPrice: int = 0
def adds(self, item: str) -> None:
'''Add the user's item into list (basket).'''
if item in self.items:
self.userSelectedItems.append(item)
else:
print(f"Item is not availabel!")
def total(self) -> int:
'''Sums all the items price.'''
self.totalPrice = 0
for item in self.userSelectedItems:
self.totalPrice += self.items[item]
return self.totalPrice


We can glean many valuable concepts from these code examples. If you have time, I encourage you to experiment by writing your own code and observing the results.

That’s all for today. Have a wonderful day!