fork download
  1.  
  2. import mysql.connector
  3.  
  4. class Supermarket:
  5. def __init__(self, host, user, password, database):
  6. self.db = mysql.connector.connect(host=host,user=user,
  7. password=password,database=database)
  8. self.cursor = self.db.cursor()
  9. self.create_table()
  10.  
  11. def create_table(self):
  12. self.cursor.execute("""CREATE TABLE IF NOT EXISTS items (id INT
  13. AUTO_INCREMENT PRIMARY KEY,name VARCHAR(255) NOT NULL,quantity INT
  14. NOT NULL,price FLOAT NOT NULL)""")
  15. self.db.commit()
  16.  
  17. def print_bill(self, purchased_items):
  18. total_amount = 0
  19. print("\n------------ Bill ------------\n")
  20. for item in purchased_items:
  21. print(f"Item: {item['name']}")
  22. print(f"Quantity: {item['quantity']}")
  23. print(f"Price: {item['price']}")
  24. print("------------------------------\n")
  25. total_amount += item["price"] * item["quantity"]
  26. print(f"Total Amount: {total_amount}\n")
  27.  
  28. def add_item(self, name, quantity, price):
  29. self.cursor.execute("""
  30. INSERT INTO items (name, quantity, price)
  31. VALUES (%s, %s, %s)""", (name, quantity, price))
  32. self.db.commit()
  33. self.update_item_list()
  34.  
  35. def purchase_items(self, purchases):
  36. purchased_items = []
  37. for purchase in purchases:
  38. purchase_item, purchase_quantity = map(str.strip, purchase.split(":"))
  39.  
  40. self.cursor.execute("SELECT * FROM items WHERE LOWER(name) = LOWER(%s))", (purchase_item,))
  41. item = self.cursor.fetchone()
  42.  
  43. if item:
  44. if item[2] >= int(purchase_quantity):
  45. new_quantity = item[2] - int(purchase_quantity)
  46. self.cursor.execute(
  47. "UPDATE items SET quantity=%s WHERE id=%s",
  48. (new_quantity, item[0]))
  49. self.db.commit()
  50.  
  51. purchased_items.append({
  52. "name": item[1],
  53. "quantity": int(purchase_quantity),
  54. "price": item[3]})
  55. else:
  56. print(f"Not enough stock for {purchase_item}")
  57. else:
  58. print(f"{purchase_item} not found in store")
  59.  
  60. self.print_bill(purchased_items)
  61.  
  62. def update_item_list(self):
  63. print("\n---------- Item List ----------")
  64. self.cursor.execute("SELECT * FROM items")
  65. for item in self.cursor.fetchall():
  66. print(f"{item[1]} - Stock: {item[2]} - Price: {item[3]}")
  67. print("-------------------------------\n")
  68.  
  69. def main():
  70. sm = Supermarket(host="localhost", user="root", password="", database ="supermarket")
  71.  
  72. purchased_items = []
  73.  
  74. while True:
  75. print("1. Add Item")
  76. print("2. Purchase Items")
  77. print("3. Display Bill")
  78. print("4. Display Stock")
  79. print("5. Exit")
  80.  
  81. choice = input("Enter your choice (1/2/3/4/5): ")
  82.  
  83. if choice == "1":
  84. name = input("Enter item name: ")
  85. quantity = int(input("Enter quantity: "))
  86. price = float(input("Enter price: "))
  87. sm.add_item(name, quantity, price)
  88.  
  89. elif choice == "2":
  90. purchases = input("Enter item name and quantity (e.g., Apple:2,
  91. Milk:1): ")
  92. purchase_list = purchases.split(",")
  93. sm.purchase_items(purchase_list)
  94.  
  95. elif choice == "3":
  96. print("Bill will be shown after purchase.")
  97.  
  98. elif choice == "4":
  99. print("Displaying Stock:")
  100. sm.update_item_list()
  101.  
  102. elif choice == "5":
  103. print("Exiting the Supermarket Management System. Goodbye!")
  104. break
  105.  
  106. else:
  107. print("Invalid choice. Please try again.\n")
  108.  
  109. if __name__ == "__main__":
  110. main()
Success #stdin #stdout 0.02s 25760KB
stdin
Standard input is empty
stdout
import mysql.connector

class Supermarket:
  def __init__(self, host, user, password, database):
    self.db = mysql.connector.connect(host=host,user=user,
    password=password,database=database)
    self.cursor = self.db.cursor()
    self.create_table()

  def create_table(self):
    self.cursor.execute("""CREATE TABLE IF NOT EXISTS items (id INT
AUTO_INCREMENT PRIMARY KEY,name VARCHAR(255) NOT NULL,quantity INT
NOT NULL,price FLOAT NOT NULL)""")
    self.db.commit()
  
  def print_bill(self, purchased_items):
    total_amount = 0
    print("\n------------ Bill ------------\n")
    for item in purchased_items:
      print(f"Item: {item['name']}")
      print(f"Quantity: {item['quantity']}")
      print(f"Price: {item['price']}")
      print("------------------------------\n")
      total_amount += item["price"] * item["quantity"]
    print(f"Total Amount: {total_amount}\n")

  def add_item(self, name, quantity, price):
    self.cursor.execute("""
      INSERT INTO items (name, quantity, price)
      VALUES (%s, %s, %s)""", (name, quantity, price))
    self.db.commit()
    self.update_item_list()
  
  def purchase_items(self, purchases):
    purchased_items = []
    for purchase in purchases:
      purchase_item, purchase_quantity = map(str.strip, purchase.split(":"))
      
      self.cursor.execute("SELECT * FROM items WHERE LOWER(name) = LOWER(%s))", (purchase_item,))
      item = self.cursor.fetchone()
      
      if item:
        if item[2] >= int(purchase_quantity):
          new_quantity = item[2] - int(purchase_quantity)
          self.cursor.execute(
            "UPDATE items SET quantity=%s WHERE id=%s",
            (new_quantity, item[0]))
          self.db.commit()

          purchased_items.append({
            "name": item[1],
            "quantity": int(purchase_quantity),
            "price": item[3]})
        else:
          print(f"Not enough stock for {purchase_item}")
      else:
        print(f"{purchase_item} not found in store")

      self.print_bill(purchased_items)

  def update_item_list(self):
    print("\n---------- Item List ----------")
    self.cursor.execute("SELECT * FROM items")
    for item in self.cursor.fetchall():
      print(f"{item[1]} - Stock: {item[2]} - Price: {item[3]}")
    print("-------------------------------\n")

def main():
  sm = Supermarket(host="localhost", user="root", password="", database ="supermarket")
  
  purchased_items = []
  
  while True:
    print("1. Add Item")
    print("2. Purchase Items")
    print("3. Display Bill")
    print("4. Display Stock")
    print("5. Exit")

    choice = input("Enter your choice (1/2/3/4/5): ")
  
    if choice == "1":
      name = input("Enter item name: ")
      quantity = int(input("Enter quantity: "))
      price = float(input("Enter price: "))
      sm.add_item(name, quantity, price)
        
    elif choice == "2":
      purchases = input("Enter item name and quantity (e.g., Apple:2,
      Milk:1): ")
      purchase_list = purchases.split(",")
      sm.purchase_items(purchase_list)
        
    elif choice == "3":
      print("Bill will be shown after purchase.")

    elif choice == "4":
      print("Displaying Stock:")
      sm.update_item_list()
        
    elif choice == "5":
      print("Exiting the Supermarket Management System. Goodbye!")
      break
      
    else:
      print("Invalid choice. Please try again.\n")

if __name__ == "__main__":
  main()