py代码实现超市管理系统
时间: 2023-12-29 11:01:49 浏览: 53
以下是一个基本的超市管理系统的 Python 代码实现:
```python
import time
class Item:
def __init__(self, name, price, quantity):
self.name = name
self.price = price
self.quantity = quantity
class Supermarket:
def __init__(self):
self.items = []
def add_item(self, item):
self.items.append(item)
def remove_item(self, name):
for i in self.items:
if i.name == name:
self.items.remove(i)
return True
return False
def display_items(self):
print("Items in stock:")
print("Name\tPrice\tQuantity")
for i in self.items:
print(i.name + "\t" + str(i.price) + "\t" + str(i.quantity))
def search_item(self, name):
for i in self.items:
if i.name == name:
return i
return None
def buy_item(self, name, quantity):
item = self.search_item(name)
if item is not None and item.quantity >= quantity:
item.quantity -= quantity
print("Purchase successful.")
print("Total cost: " + str(item.price * quantity))
else:
print("Item not available or quantity not sufficient.")
if __name__ == "__main__":
market = Supermarket()
# add some items to the market
market.add_item(Item("Apple", 1.5, 10))
market.add_item(Item("Banana", 1, 15))
market.add_item(Item("Orange", 2, 5))
while True:
print("\nWelcome to the supermarket!")
print("1. Display items")
print("2. Search item")
print("3. Buy item")
print("4. Exit")
choice = input("Enter your choice: ")
if choice == "1":
market.display_items()
elif choice == "2":
name = input("Enter item name: ")
item = market.search_item(name)
if item is not None:
print("Item found:")
print("Name: " + item.name)
print("Price: " + str(item.price))
print("Quantity: " + str(item.quantity))
else:
print("Item not found.")
elif choice == "3":
name = input("Enter item name: ")
quantity = int(input("Enter quantity: "))
market.buy_item(name, quantity)
elif choice == "4":
print("Thanks for shopping with us!")
time.sleep(2)
break
else:
print("Invalid choice. Please try again.")
```
这个超市管理系统允许用户浏览库存、搜索商品、购买商品等操作。用户可以根据菜单选项输入数字选择要执行的操作。