DEV Community

Venkateswara Reddy
Venkateswara Reddy

Posted on • Updated on

shopping cart working in progress....>

python script:

def main():
    print("Welcome to the Shop!")

    # Asking for user details
    name = input("Please enter your name: ")
    age = input("Please enter your age: ")

    print(f"Hello {name}, welcome to our shop!")

    # List of vegetables and their prices
    vegetables = [
        ("Tomato", 2.50),
        ("Potato", 1.20),
        ("Onion", 1.00),
        ("Carrot", 1.50),
        ("Broccoli", 2.80),
        ("Spinach", 1.75),
        ("Cabbage", 1.10),
        ("Pepper", 3.00),
        ("Cauliflower", 2.30),
        ("Mushroom", 4.00)
    ]

    # List of fashion items and their prices
    fashion_items = [
        ("T-Shirt", 10.00),
        ("Jeans", 25.00),
        ("Jacket", 50.00),
        ("Skirt", 20.00),
        ("Dress", 40.00),
        ("Shoes", 30.00),
        ("Hat", 15.00),
        ("Scarf", 12.00),
        ("Sweater", 35.00),
        ("Socks", 5.00)
    ]

    # List of fruits and their prices
    fruits = [
        ("Apple", 3.00),
        ("Banana", 1.50),
        ("Orange", 2.00),
        ("Grapes", 4.00),
        ("Pineapple", 2.50),
        ("Mango", 2.80),
        ("Strawberry", 5.00),
        ("Blueberry", 6.00),
        ("Watermelon", 3.50),
        ("Cherry", 7.00)
    ]

    # List of snack items and their prices
    snacks = [
        ("Chips", 1.50),
        ("Cookies", 3.00),
        ("Candy", 2.00),
        ("Chocolate", 2.50),
        ("Popcorn", 1.80),
        ("Nuts", 4.50),
        ("Granola Bar", 2.20),
        ("Pretzels", 1.90),
        ("Crackers", 3.20),
        ("Trail Mix", 4.00)
    ]

    total_cost = 0
    veg_cart = []
    fashion_cart = []
    fruit_cart = []
    snack_cart = []

    while True:
        print("\nWhat would you like to purchase today?")
        print("1. Vegetables")
        print("2. Fashion Items")
        print("3. Fruits")
        print("4. Snacks")
        print("0. Exit")

        try:
            category_choice = int(input("Please enter the number corresponding to your choice: "))

            if category_choice == 0:
                break
            elif category_choice == 1:
                total_cost = shop_items("Vegetables", vegetables, veg_cart, total_cost)
            elif category_choice == 2:
                total_cost = shop_items("Fashion Items", fashion_items, fashion_cart, total_cost)
            elif category_choice == 3:
                total_cost = shop_items("Fruits", fruits, fruit_cart, total_cost)
            elif category_choice == 4:
                total_cost = shop_items("Snacks", snacks, snack_cart, total_cost)
            else:
                print("Invalid choice. Please select a valid option.")
        except ValueError:
            print("Invalid input. Please enter a number.")

        # Asking if the user wants to continue shopping in a different category or exit
        while True:
            continue_shopping = input("Would you like to continue shopping in a different category? (y/n): ").lower()
            if continue_shopping in ['y', 'n']:
                break
            else:
                print("Invalid input. Please enter 'y' for yes or 'n' for no.")

        if continue_shopping == 'n':
            break

    # Generate the invoice
    print_invoice(veg_cart, fashion_cart, fruit_cart, snack_cart, total_cost)

def shop_items(category_name, items_list, shopping_cart, total_cost):
    print(f"\nHere's a list of {category_name.lower()} and their prices:")
    for i, (item, price) in enumerate(items_list, 1):
        print(f"{i}. {item}: ${price:.2f}")

    while True:
        try:
            choice_num = int(input(f"\nEnter the number of the {category_name.lower()} you would like to buy (type '0' to finish shopping in this category): "))

            if choice_num == 0:
                break

            if 1 <= choice_num <= len(items_list):
                item_name, item_price = items_list[choice_num - 1]
                try:
                    quantity = float(input(f"How many units of {item_name} would you like to buy? "))
                    cost = item_price * quantity
                    total_cost += cost
                    shopping_cart.append((item_name, quantity, cost))
                    print(f"You added {quantity} unit(s) of {item_name} costing ${cost:.2f} to your cart.")
                except ValueError:
                    print("Invalid input for quantity. Please enter a valid number.")
            else:
                print(f"Invalid choice. Please enter a number between 1 and {len(items_list)}.")

        except ValueError:
            print("Invalid input. Please enter a number.")

        while True:
            more_shopping = input("Would you like to buy anything else in this category? (y/n): ").lower()
            if more_shopping in ['y', 'n']:
                break
            else:
                print("Invalid input. Please enter 'y' for yes or 'n' for no.")

        if more_shopping == 'n':
            break

    return total_cost

def print_invoice(veg_cart, fashion_cart, fruit_cart, snack_cart, total_cost):
    veg_total = sum(item[2] for item in veg_cart)
    fashion_total = sum(item[2] for item in fashion_cart)
    fruit_total = sum(item[2] for item in fruit_cart)
    snack_total = sum(item[2] for item in snack_cart)

    print("\nThank you for shopping with us!")
    print("Here's your invoice:")

    if veg_cart:
        print("-------------------------------------------------")
        print(f"{'Vegetables':<15}{'Quantity (kg)':<15}{'Cost ($)':<15}")
        print("-------------------------------------------------")
        for item in veg_cart:
            print(f"{item[0]:<15}{item[1]:<15.2f}{item[2]:<15.2f}")
        print(f"{'Subtotal (Vegetables)':<30}{veg_total:.2f}")

    if fashion_cart:
        print("-------------------------------------------------")
        print(f"{'Fashion Items':<15}{'Quantity':<15}{'Cost ($)':<15}")
        print("-------------------------------------------------")
        for item in fashion_cart:
            print(f"{item[0]:<15}{item[1]:<15.2f}{item[2]:<15.2f}")
        print(f"{'Subtotal (Fashion)':<30}{fashion_total:.2f}")

    if fruit_cart:
        print("-------------------------------------------------")
        print(f"{'Fruits':<15}{'Quantity (kg)':<15}{'Cost ($)':<15}")
        print("-------------------------------------------------")
        for item in fruit_cart:
            print(f"{item[0]:<15}{item[1]:<15.2f}{item[2]:<15.2f}")
        print(f"{'Subtotal (Fruits)':<30}{fruit_total:.2f}")

    if snack_cart:
        print("-------------------------------------------------")
        print(f"{'Snacks':<15}{'Quantity':<15}{'Cost ($)':<15}")
        print("-------------------------------------------------")
        for item in snack_cart:
            print(f"{item[0]:<15}{item[1]:<15.2f}{item[2]:<15.2f}")
        print(f"{'Subtotal (Snacks)':<30}{snack_total:.2f}")

    print("-------------------------------------------------")
    print(f"{'Total':<30}{total_cost:.2f}")
    print("-------------------------------------------------")
    print("We hope to see you again, goodbye!")

if __name__ == "__main__":
    main()

Enter fullscreen mode Exit fullscreen mode

For UI Tkinter script:

import tkinter as tk
from tkinter import messagebox

def main():
    root = tk.Tk()
    root.title("Shop Interface")
    root.configure(bg="#F0F8FF")  # Light blue background

    # User Details Section
    tk.Label(root, text="Please enter your name:", bg="#F0F8FF", font=("Helvetica", 12)).grid(row=0, column=0, padx=10, pady=5, sticky="w")
    name_entry = tk.Entry(root, font=("Helvetica", 12))
    name_entry.grid(row=0, column=1, padx=10, pady=5)

    tk.Label(root, text="Please enter your age:", bg="#F0F8FF", font=("Helvetica", 12)).grid(row=1, column=0, padx=10, pady=5, sticky="w")
    age_entry = tk.Entry(root, font=("Helvetica", 12))
    age_entry.grid(row=1, column=1, padx=10, pady=5)

    # Categories List
    categories = ["Vegetables", "Fashion Items", "Fruits", "Snacks"]
    items = {
        "Vegetables": [
            ("Tomato", 2.50), ("Potato", 1.20), ("Onion", 1.00), ("Carrot", 1.50),
            ("Broccoli", 2.80), ("Spinach", 1.75), ("Cabbage", 1.10), ("Pepper", 3.00),
            ("Cauliflower", 2.30), ("Mushroom", 4.00)
        ],
        "Fashion Items": [
            ("T-Shirt", 10.00), ("Jeans", 25.00), ("Jacket", 50.00), ("Skirt", 20.00),
            ("Dress", 40.00), ("Shoes", 30.00), ("Hat", 15.00), ("Scarf", 12.00),
            ("Sweater", 35.00), ("Socks", 5.00)
        ],
        "Fruits": [
            ("Apple", 3.00), ("Banana", 1.50), ("Orange", 2.00), ("Grapes", 4.00),
            ("Pineapple", 2.50), ("Mango", 2.80), ("Strawberry", 5.00), ("Blueberry", 6.00),
            ("Watermelon", 3.50), ("Cherry", 7.00)
        ],
        "Snacks": [
            ("Chips", 1.50), ("Cookies", 3.00), ("Candy", 2.00), ("Chocolate", 2.50),
            ("Popcorn", 1.80), ("Nuts", 4.50), ("Granola Bar", 2.20), ("Pretzels", 1.90),
            ("Crackers", 3.20), ("Trail Mix", 4.00)
        ]
    }

    # Function to add items to cart
    def add_to_cart():
        category = category_var.get()
        item = item_var.get()
        quantity = quantity_var.get()
        if not category or not item or not quantity:
            messagebox.showerror("Input Error", "Please fill in all fields.")
            return

        try:
            quantity = float(quantity)
            item_name, item_price = item.split(": $")
            item_price = float(item_price)
            cost = item_price * quantity
            cart.append((category, item_name, quantity, cost))
            messagebox.showinfo("Added to Cart", f"Added {quantity} unit(s) of {item_name} costing ${cost:.2f} to your cart.")
        except ValueError:
            messagebox.showerror("Input Error", "Please enter a valid quantity.")

    # Function to generate invoice
    def generate_invoice():
        if not cart:
            messagebox.showwarning("Empty Cart", "Your cart is empty.")
            return

        total_cost = sum(item[3] for item in cart)
        invoice_window = tk.Toplevel(root)
        invoice_window.title("Invoice")
        invoice_window.configure(bg="#FFFACD")  # Light golden background

        tk.Label(invoice_window, text=f"Name: {name_entry.get()}", bg="#FFFACD", font=("Helvetica", 12)).pack(padx=10, pady=5)
        tk.Label(invoice_window, text=f"Age: {age_entry.get()}", bg="#FFFACD", font=("Helvetica", 12)).pack(padx=10, pady=5)
        tk.Label(invoice_window, text="Your Invoice:", bg="#FFFACD", font=("Helvetica", 14, "bold")).pack(padx=10, pady=5)

        for category in categories:
            category_items = [item for item in cart if item[0] == category]
            if category_items:
                tk.Label(invoice_window, text=f"--- {category} ---", bg="#FFFACD", font=("Helvetica", 12, "italic")).pack(padx=10, pady=5)
                for item in category_items:
                    tk.Label(invoice_window, text=f"{item[1]}: {item[2]} units, ${item[3]:.2f}", bg="#FFFACD", font=("Helvetica", 12)).pack(padx=10, pady=2)

        tk.Label(invoice_window, text=f"Total: ${total_cost:.2f}", bg="#FFFACD", font=("Helvetica", 14, "bold")).pack(padx=10, pady=10)
        tk.Button(invoice_window, text="Close", command=invoice_window.destroy, bg="#FFD700", font=("Helvetica", 12)).pack(pady=10)

    cart = []
    category_var = tk.StringVar()
    item_var = tk.StringVar()
    quantity_var = tk.StringVar()

    # Dropdown for categories
    tk.Label(root, text="Select Category:", bg="#F0F8FF", font=("Helvetica", 12)).grid(row=2, column=0, padx=10, pady=5, sticky="w")
    category_menu = tk.OptionMenu(root, category_var, *categories)
    category_menu.grid(row=2, column=1, padx=10, pady=5)
    category_menu.config(bg="#E6E6FA", font=("Helvetica", 12))  # Lavender background

    # Function to update items based on selected category
    def update_items(*args):
        category = category_var.get()
        if category:
            items_list = [f"{name}: ${price:.2f}" for name, price in items[category]]
            item_menu["menu"].delete(0, "end")
            for item in items_list:
                item_menu["menu"].add_command(label=item, command=tk._setit(item_var, item))

    category_var.trace("w", update_items)

    # Dropdown for items
    tk.Label(root, text="Select Item:", bg="#F0F8FF", font=("Helvetica", 12)).grid(row=3, column=0, padx=10, pady=5, sticky="w")
    item_menu = tk.OptionMenu(root, item_var, "")
    item_menu.grid(row=3, column=1, padx=10, pady=5)
    item_menu.config(bg="#E6E6FA", font=("Helvetica", 12))  # Lavender background

    # Quantity input
    tk.Label(root, text="Enter Quantity:", bg="#F0F8FF", font=("Helvetica", 12)).grid(row=4, column=0, padx=10, pady=5, sticky="w")
    tk.Entry(root, textvariable=quantity_var, font=("Helvetica", 12)).grid(row=4, column=1, padx=10, pady=5)

    # Buttons for adding to cart and generating invoice
    tk.Button(root, text="Add to Cart", command=add_to_cart, bg="#7FFFD4", font=("Helvetica", 12)).grid(row=5, column=0, padx=10, pady=10)
    tk.Button(root, text="Generate Invoice", command=generate_invoice, bg="#7FFFD4", font=("Helvetica", 12)).grid(row=5, column=1, padx=10, pady=10)

    root.mainloop()

if __name__ == "__main__":
    main()

Enter fullscreen mode Exit fullscreen mode
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Welcome to Our Shopping Store</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }
        .container {
            max-width: 600px;
            margin: auto;
            text-align: center;
        }
        .btn {
            display: inline-block;
            padding: 10px 20px;
            margin: 10px;
            font-size: 16px;
            cursor: pointer;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 5px;
            text-decoration: none;
        }
        .btn:hover {
            background-color: #b3001e;
        }
        .hidden {
            display: none;
        }
        /* Background Colors for Sections */
        #welcome {
            background-color: #007bff; /* Blue */
            color: white;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
        }
        #registration {
            background-color: #28a745; /* Green */
            color: white;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
        }
        #login {
            background-color: #ffc107; /* Yellow */
            color: black;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
        }
        #shopping {
            background-color: #dc3545; /* Red */
            color: white;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- Welcome Section -->
        <div id="welcome">
            <h1>Hello My Dear Customer!</h1>
            <h2>Welcome to Our Shopping Store</h2>
            <button class="btn" onclick="showRegistration()">New User</button>
            <button class="btn" onclick="showLogin()">Existing User</button>
        </div>

        <!-- Registration Section -->
        <div id="registration" class="hidden">
            <h3>New User Registration</h3>
            <form id="registrationForm">
                <label for="username">Username:</label><br>
                <input type="text" id="username" name="username" required><br><br>

                <label for="gender">Gender:</label><br>
                <select id="gender" name="gender" required>
                    <option value="">Select Gender</option>
                    <option value="male">Male</option>
                    <option value="female">Female</option>
                    <option value="transgender">Transgender</option>
                    <option value="not_specified">Don't Want to Tell</option>
                </select><br><br>

                <label for="age">Age:</label><br>
                <input type="number" id="age" name="age" min="0" max="100" required><br><br>

                <label for="password">Password:</label><br>
                <input type="password" id="password" name="password" required><br><br>

                <button type="submit" class="btn">Register</button>
            </form>
        </div>

        <!-- Login Section -->
        <div id="login" class="hidden">
            <h3>Existing User Login</h3>
            <form id="loginForm">
                <label for="existingUsername">Username:</label><br>
                <input type="text" id="existingUsername" name="existingUsername" required><br><br>

                <label for="existingPassword">Password:</label><br>
                <input type="password" id="existingPassword" name="existingPassword" required><br><br>

                <button type="submit" class="btn">Login</button>
            </form>
        </div>

        <!-- Shopping Section -->
        <div id="shopping" class="hidden">
            <h3>Please Start Your Shopping</h3>
            <button class="btn" onclick="backToWelcome()">Back to Welcome</button>
            <!-- Additional shopping content can go here -->
        </div>
    </div>

    <script>
        function showRegistration() {
            document.getElementById('welcome').style.display = 'none';
            document.getElementById('registration').style.display = 'block';
            document.getElementById('shopping').style.display = 'none';
        }

        function showLogin() {
            document.getElementById('welcome').style.display = 'none';
            document.getElementById('login').style.display = 'block';
            document.getElementById('shopping').style.display = 'none';
        }

        function backToWelcome() {
            document.getElementById('welcome').style.display = 'block';
            document.getElementById('registration').style.display = 'none';
            document.getElementById('login').style.display = 'none';
            document.getElementById('shopping').style.display = 'none';
        }

        document.getElementById('registrationForm').addEventListener('submit', function(event) {
            event.preventDefault();
            // Here you can handle the registration form submission with JavaScript or send it to a backend server
            document.getElementById('registration').style.display = 'none';
            document.getElementById('shopping').style.display = 'block';
        });

        document.getElementById('loginForm').addEventListener('submit', function(event) {
            event.preventDefault();
            // Here you can handle the login form submission with JavaScript or send it to a backend server
            document.getElementById('login').style.display = 'none';
            document.getElementById('shopping').style.display = 'block';
        });
    </script>
</body>
</html>

Enter fullscreen mode Exit fullscreen mode

Top comments (0)