Day 5 - Python

Problem Statement: Online Shopping Cart System

You are required to implement an online shopping cart system with the following functionalities:

Add to Cart: Implement a function add_to_cart(cart, product_id, product_name, product_price, quantity) which adds a specified quantity of a product to the shopping cart. If the product is already in the cart, the quantity should be updated. If not, it should be added to the cart.

Remove from Cart: Implement a function remove_from_cart(cart, product_id) which removes a product from the cart based on its ID.

Calculate Total: Implement a function calculate_total(cart) which calculates the total price of all the products in the cart.

View Cart: Implement a function view_cart(cart) which displays the contents of the cart including product ID, name, price, and quantity.

Write a program that takes input in the following format:

1: Add to Cart

Arguments: <product_id> <product_name> <product_price> <quantity>

2: Remove from Cart

Arguments: <product_id>

3: Calculate Total

4: View Cart

You need to implement the necessary functions and ensure the program behaves as described.

Input:

The input will contain multiple lines, each representing an operation as described above.

Output:

For each "Add to Cart" operation, output a message indicating that the product has been added. For each "Remove from Cart" operation, output a message indicating that the product has been removed. For each "View Cart" operation, output the contents of the cart in tabular format showing Product ID, Product Name, Price, and Quantity. Additionally, for "Calculate Total", output the total price of products in the cart.

Sample Input:

1 101 Shirt 25.5 2

1 102 Jeans 45.75 1

3

2 101

1 103 Shoes 35.0 1

4

Sample Output:

101 added

102 added

Total price of products in the cart: 71.25

101 removed

103 added

   Product ID Product Name  Price  Quantity

0         102        Jeans  45.75         1

1         103        Shoes  35.00         1

Total price of products in the cart: 80.75

This problem assesses your ability to implement basic data manipulation with lists, dictionaries, and functions in Python, along with input/output handling and DataFrame creation using pandas.

Complete Execution Output:

1 101 Shirt 25.5 2

101 added

1 102 Jeans 45.75 1

102 added

3

Total price of products in the cart: 96.75

2 101

101 removed

1 103 Shoes 35.0 1

103 added

4

   Product ID Product Name  Price  Quantity

0         102        Jeans  45.75         1

1         103        Shoes  35.00         1

Total price of products in the cart: 80.75


SOLUTION

import pandas as pd

def add_to_cart(cart, product_id, product_name, product_price, quantity):

    for item in cart:

        if item["id"] == product_id:

            item["quantity"] += quantity

            return

    cart.append({"id": product_id, "name": product_name, "price": product_price, "quantity": quantity})

    print(product_id,"added")


def remove_from_cart(cart, product_id):

    cart[:] = [item for item in cart if item["id"] != product_id]

    print(product_id,"removed")


def calculate_total(cart):

    return sum(item["price"] * item["quantity"] for item in cart)


cart = []

while True:

    user_input = input().split()

    op = int(user_input[0])

    if op == 1:

        product_id, product_name, product_price, quantity = user_input[1:]

        product_id = int(product_id)

        product_price = float(product_price)

        quantity = int(quantity)

        add_to_cart(cart, product_id, product_name, product_price, quantity)

    elif op == 2:

        product_id = int(user_input[1])

        remove_from_cart(cart, product_id)

    elif op == 3:

        total_price = calculate_total(cart)

        print("Total price of products in the cart:", total_price)

    elif op == 4:

        cart_data = {

            "Product ID": [item["id"] for item in cart],

            "Product Name": [item["name"] for item in cart],

            "Price": [item["price"] for item in cart],

            "Quantity": [item["quantity"] for item in cart]

        }

        if(len(cart)!=0):

          df = pd.DataFrame(cart_data)

          print(df)

          total_price = calculate_total(cart)

          print("Total price of products in the cart:", total_price)

        break

    else:

        print("Invalid")


Insights:

  • The implementation uses a list of dictionaries to represent the cart. This choice allows for easy addition, removal, and modification of items in the cart.
  • The program splits user input to extract operation and arguments. This approach assumes well-formatted input.
  • Try adding try..except blocks for wrong format inputs.
  • The program utilizes pandas to create a DataFrame for displaying cart contents. While pandas is a powerful tool for data manipulation, for smaller datasets, using simpler data structures or formatting directly might be more efficient.
  • Functions are well-segmented based on functionality, promoting a modular design. This makes the code easier to understand, maintain, and debug.
Explore the small small parts in this code carefully. Try incorporating in a different domain!
Learn Pandas! Explore Coding! :)



Comments