Python Use a Class to Simulate an Online Shopping Cart Supporting Add and Remove Operations
We will use a Python class to simulate an online shopping cart. The cart will support adding products, removing products, viewing its contents and calculating the total price.
Example
class
ShoppingCart:
def
init
(
self
)
:
self
.
items
=
[
]
def
add_item
(
self
,
name
,
price
,
quantity
=
1
)
:
self
.
items
.
append
(
{
'name'
: name
,
'price'
: price
,
'quantity'
: quantity
}
)
def
remove_item
(
self
,
name
)
:
self
.
items
=
[
item
for
item
in
self
.
items
if
item
[
'name'
]
!=
name
]
def
view_cart
(
self
)
:
if
not
self
.
items
:
(
"Your shopping cart is empty."
)
else
:
for
item
in
self
.
items
:
(
f
"{item['name']} - ${item['price']} x {item['quantity']}"
)
def
calculate_total
(
self
)
:
return
sum
(
item
[
'price'
]
- item
[
'quantity'
]
for
item
in
self
.
items
)
Example usage
cart
=
ShoppingCart
(
)
cart.
add_item
(
"Apple"
,
0.5
,
3
)
cart.
add_item
(
"Banana"
,
0.3
,
5
)
cart.
view_cart
(
)
(
f
"Total: ${cart.calculate_total()}"
)
cart.
remove_item
(
"Banana"
)
cart.
view_cart
(
)
(
f
"Total: ${cart.calculate_total()}"
)
Code analysis:
__init__The method initializes the cart, creating an empty listitemsto store the products.add_itemThe method adds a product to the cart; it takes the product name, price and quantity (default 1) as parameters and adds it toitemslist.remove_itemThe method removes a product with the specified name from the cart, using a list comprehension to filter out the unwanted product.view_cartThe method displays the products in the cart; if the cart is empty it reports that the cart is empty, otherwise it iterates over theitemslist and prints the details of each product.calculate_totalThe method calculates the total price of all products in the cart, implemented with a list comprehension and thesumfunction.
Output result:
Apple - $0.5 x 3
Banana - $0.3 x 5
Total: $2.4
Apple - $0.5 x 3
Total: $1.5
Python3 Examples