CREATE DATABASE shopping_db;
USE shopping_db;
CREATE TABLE items (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
price INT
);
INSERT INTO items (name, price) VALUES
('Rice', 160),
('Potato', 80),
('Tomato', 70),
('Wheat', 150),
('Pulses', 180),
('Onion', 100),
('Sugar', 80),
('Salt', 60),
('Spices', 100);
import mysql.connector
# Establish a connection to the database
db = mysql.connector.connect(
host="localhost", # Change to your MySQL host
user="root", # MySQL username
password="yourpassword", # MySQL password
database="shopping_db" # Database name
)
cursor = db.cursor()
# Function to display available items
def display_items():
cursor.execute("SELECT id, name, price FROM items")
items = cursor.fetchall()
print("\nAvailable items:")
for item in items:
print(f"{item[0]}. {item[1]} - Rs. {item[2]}")
# Function to handle item selection
def select_items():
selected_items = []
while True:
try:
item_id = int(input("\nEnter the item ID to select (or 0 to finish): "))
if item_id == 0:
break
cursor.execute("SELECT name, price FROM items WHERE id = %s", (item_id,))
item = cursor.fetchone()
if item:
selected_items.append(item)
print(f"Added {item[0]} to the cart.")
else:
print("Invalid item ID. Please try again.")
except ValueError:
print("Please enter a valid number.")
return selected_items
# Function to calculate total price
def calculate_bill(selected_items):
total_price = sum(item[1] for item in selected_items)
return total_price
# Function to print the bill
def print_bill(selected_items, total_price):
print("\nFinal Bill:")
print("------------")
for item in selected_items:
print(f"{item[0]} - Rs. {item[1]}")
print(f"Total: Rs. {total_price}")
def main():
display_items() # Show available items
selected_items = select_items() # Allow user to select items
if selected_items:
total_price = calculate_bill(selected_items) # Calculate total price
print_bill(selected_items, total_price) # Show final bill
else:
print("No items selected.")
# Close the database connection
db.close()
# Run the program
if _name_ == "_main_":
main()