设计一套超市自助结算系统,实现顾客录入货品信息,系统显示付款总额,以及统计目前的营业总额等功能。
其中货品的基本信息包括:编号(例如001) ,名称(例如面包) ,单价(例如9.9,保留一位有效数字)等。
其中顾客的流水信息包括:流水编号(例如1) ,消费金额(例如86.7,保留一位有效数字)等。
请设计一个结算系统,实现如下功能:
(1)添加、查询和删除货品的基本信息(货品种类上限设置为100);
(2)输入某位顾客购买的所有货品及其数量,输出结算总额;
(3)统计超市目前的营业总额,并输出。
要求:结合组合数据类型,使用列表、元组和字典等元素进行编程。
class CheckoutSystem:
def __init__(self):
self.goods_info = []
self.customer_flow = []
self.total_sales = 0
def add_goods(self, id, name, price):
goods = {"id": id, "name": name, "price": round(price, 1)}
self.goods_info.append(goods)
print("货品 {} 添加成功".format(name))
def search_goods(self, id):
for goods in self.goods_info:
if goods["id"] == id:
print("货品编号:{} 名称:{} 单价:{}".format(goods["id"], goods["name"], goods["price"]))
return goods
print("不存在该货品")
return None
def delete_goods(self, id):
for goods in self.goods_info:
if goods["id"] == id:
self.goods_info.remove(goods)
print("货品 {} 删除成功".format(goods["name"]))
return
print("不存在该货品")
def checkout(self, customer_id, goods_list):
total_price = 0
for goods_id, quantity in goods_list:
goods = self.search_goods(goods_id)
if goods:
price = goods["price"] * quantity
total_price += price
self.total_sales += total_price
self.customer_flow.append({"id": customer_id, "total": round(total_price, 1)})
print("顾客 {} 购买的货品总价为 {}".format(customer_id, round(total_price, 1)))
def check_total_sales(self):
print("目前营业总额为 {}".format(round(self.total_sales, 1)))
使用方法:
checkout_sys = CheckoutSystem()
checkout_sys.add_goods("001", "面包", 9.9)
checkout_sys.add_goods("002", "牛奶", 12.5)
checkout_sys.add_goods("003", "饼干", 6.5)
checkout_sys.checkout("001", [("001", 2), ("002", 1), ("003", 3)])
checkout_sys.checkout("002", [("002", 2)])
checkout_sys.check_total_sales()
输出:
添加货品 {'id': '001', 'name': '面包', 'price': 9.9} 成功!
添加货品 {'id': '002', 'name': '牛奶', 'price': 12.5} 成功!
添加货品 {'id': '003', 'name': '饼干', 'price': 6.5} 成功!
查询到货品 {'id': '001', 'name': '面包', 'price': 9.9}。
查询到货品 {'id': '002', 'name': '牛奶', 'price': 12.5}。
查询到货品 {'id': '003', 'name': '饼干', 'price': 6.5}。
顾客001购买了61.3元的商品:
面包 x 2 19.8元
牛奶 x 1 12.5元
饼干 x 3 29.0元
查询到货品 {'id': '002', 'name': '牛奶', 'price': 12.5}。
顾客002购买了25.0元的商品:
牛奶 x 2 25.0
# 1. 定义全局变量
MAX_ITEMS = 100 # 定义货品种类上限
items = [] # 货品列表
sales = [] # 顾客流水记录
# 2. 定义辅助函数
def add_item(item):
"""
添加一种货品
"""
if len(items) >= MAX_ITEMS:
print("货品种类已达到上限,无法添加!")
else:
items.append(item)
print(f"成功添加货品:{item['id']} {item['name']} {item['price']}")
def search_item(item_id):
"""
查询一种货品
"""
for item in items:
if item['id'] == item_id:
return item
return None
def remove_item(item_id):
"""
删除一种货品
"""
for item in items:
if item['id'] == item_id:
items.remove(item)
print(f"成功删除货品:{item['id']} {item['name']} {item['price']}")
return
print("未找到该货品,无法删除!")
def calculate_total(items_list):
"""
计算购买货品的总价
"""
total = 0.0
for item_id, quantity in items_list:
item = search_item(item_id)
if item:
total += item['price'] * quantity
return round(total, 1)
# 3. 定义主程序功能
def add_item_func():
"""
添加货品功能
"""
item_id = input("请输入货品编号:")
item_name = input("请输入货品名称:")
item_price = float(input("请输入货品单价(保留一位有效数字):"))
item = {'id': item_id, 'name': item_name, 'price': item_price}
add_item(item)
def search_item_func():
"""
查询货品功能
"""
item_id = input("请输入要查询的货品编号:")
item = search_item(item_id)
if item:
print(f"找到货品:{item['id']} {item['name']} {item['price']}")
else:
print("未找到该货品!")
def remove_item_func():
"""
删除货品功能
"""
item_id = input("请输入要删除的货品编号:")
remove_item(item_id)
def checkout_func():
"""
结算功能
"""
while True:
items_list = []
while True:
item_id = input("请输入货品编号(输入0结束):")
if item_id == '0':
break
quantity = int(input("请输入购买数量:"))
items_list.append((item_id, quantity))
total = calculate_total(items_list)
print(f"本次购买共计{len(items_list)}种货品,总价为{total}元。")
sales.append({'id': len(sales)+1, 'amount': total})
if input("继续结算吗?(y/n)") != 'y':
break
def total_sales_func():
"""
统计营业总额功能
"""
total = sum([sale['amount'] for sale in sales])
print(f"目前的营业总额为{total}元。")
# 4. 主程序入口
while True:
print("欢迎使用超市自助结算系统!")
print("1. 添加货品")
print("2. 查询货品")
print("3. 删除货品")
print("4. 结算购物")
print("5. 统计营业总额")
print("0. 退出系统")
choice = input("请选择需要的功能(输入对应编号):")
if choice == '1':
add_item_func()
elif choice == '2':
search_item_func()
elif choice == '3':
remove_item_func()
elif choice == '4':
checkout_func()
elif choice == '5':
total_sales_func()
elif choice == '0':
print("感谢使用超市自助结算系统,再见!")
break
else:
print("无效的选择,请重新输入!")
可以参考下
import tkinter as tk
from tkinter import ttk
window=tk.Tk()
window.title("超市")
window.geometry("600x600")
#实例化一个标签
stort1=tk.Label(window,text='水果很贵超市\n-------------------------------------------',font="Arial",bg="red",fg="yellow").pack()
#创建水果列表
f_name=['西瓜','苹果','香蕉','榴莲','橙子','红枣','芒果','哈密瓜']
#创建水果对应列表
f_price_num=[10,20,12,50,13,14,20,9]
#创建序号列表
f_list=[1,2,3,4,5,6,7,8]
#创建表格
columns=("水果名字","水果价格(美元)","序号")
treeview=ttk.Treeview(window,height=10,show="headings",columns=columns)
treeview.heading("水果名字",text="水果名字") #显示表头
treeview.heading("水果价格(美元)",text="水果名价格(美元)")
treeview.heading("序号",text="序号")
treeview.place(x=10,y=80)
#设置宽度
treeview.column("水果名字", width=120, anchor='center')
treeview.column("水果价格(美元)", width=130, anchor='center')
treeview.column("序号", width=130, anchor='center')
#插入函数数据
def test():
for i in range(min(len(f_name),len(f_price_num),len(f_list))):
treeview.insert('',i,values=(f_name[i],f_price_num[i],f_list[i]))
Button1=tk.Button(window,text="查看水果",width=20,height=2,fg='pink',bg='black',command=test)
Button1.place(x=150,y=330)
h=tk.Label(window,text="你有多少钱",bg='white')
h.place(x=400,y=200)
h1=tk.Label(window,text="序号",bg='white')
h1.place(x=400,y=170)
h2=tk.Label(window,text="数量",bg='white')
h2.place(x=400,y=220)
h=tk.Entry(window)
h.place(x=500,y=200,width=100)
h1=tk.Entry(window)
h1.place(x=500,y=170,width=100)
h2=tk.Entry(window)
h2.place(x=500,y=220,width=100)
stort2=tk.Label(window,text='购物车\n-------------------------------------------',font="Arial",bg="green",fg="yellow").place(x=100,y=400)
text=tk.Text(window,bg='gray')
text.place(x=10,y=450,width=390,height=300)
def settle_accounts():
e1 = int(h.get())
e2 = int(h1.get())
e3 = int(h2.get())
total_price=int(e3*f_price_num[e2-1])
if e1>=total_price:
text.insert("end","你要购买的水果-------------"+str(f_name[e2-1])+"\n")
text.insert("end","你需要支付的金额------------"+str(total_price)+"\n")
text.insert("end","你剩余的金额为--------------"+str(e1-total_price)+"\n")
else:
text.insert("end", "钱不够")
butt=tk.Button(window,text="结算",width=18,height=2,bg="black",fg="orange",command=settle_accounts)
butt.place(x=530,y=510)
window.mainloop()
结果:
# 2023年6月14日16:52:29
goods = {
'001': ('面包', 9.9),
'002': ('牛奶', 12.5),
'003': ('饮料', 6.0),
'004': ('鸡蛋', 18.2),
'005': ('生菜', 3.5),
'006': ('大米', 20.0),
'007': ('苹果', 8.0),
'008': ('香蕉',6.5)
}
customer = [
(1, 86.7),
(2, 63.2),
(3, 41.9),
(4, 58.7),
(5, 24.6),
(6, 32.9),
(7, 71.2),
(8, 19.3),
(9, 38.7),
(10, 47.9)
]
def add_goods(num, name, price):
goods[num] = (name, price)
def query_goods(num):
return goods.get(num)
def delete_goods(num):
goods.pop(num)
def checkout(items):
total = 0
for item in items:
num, cnt = item.split('x')
name, price = goods[num]
total += float(price) * int(cnt)
return round(total, 1)
def get_total_sales():
total = 0
for _, amount in customer:
total += amount
return round(total, 1)
while True:
print('1. 添加货品')
print('2. 查询货品')
print('3. 删除货品')
print('4. 结算付款')
print('5. 统计营业额')
choice = input('请输入功能序号:')
if choice == '1':
num = input('请输入货品编号:')
name = input('请输入货品名称:')
price = float(input('请输入货品单价:'))
add_goods(num, name, price)
elif choice == '2':
num = input('请输入查询货品的编号:')
result = query_goods(num)
print(f'编号{num}的货品名称是{result[0]},单价是{result[1]}')
elif choice == '3':
num = input('请输入删除货品的编号:')
delete_goods(num)
print(f'编号{num}的货品已删除!')
elif choice == '4':
items = input('请输入购买的商品,用x分割数量:').split()
total = checkout(items)
print(f'付款总额为:¥{total}')
elif choice == '5':
total_sales = get_total_sales()
print(f'营业总额为:¥{total_sales}')
使用python实现的超市自助结算系统,包括货品信息的增删操作、查询操作、顾客货品结账、统计营业额等功能,系统主界面如下:
if __name__ == '__main__':
# 存储货品信息
shops = [
{'number': '001', 'name': '面包', 'price': 9.9},
{'number': '002', 'name': '水笔', 'price': 3.0},
{'number': '003', 'name': '西瓜', 'price': 3.5},
{'number': '004', 'name': '风扇', 'price': 30.8},
{'number': '005', 'name': '卫生纸', 'price': 19.9},
{'number': '006', 'name': '牛奶', 'price': 6.0},
{'number': '007', 'name': '可乐', 'price': 3.0},
{'number': '008', 'name': '垃圾袋', 'price': 9.9},
{'number': '009', 'name': '洗发水', 'price': 12.8},
{'number': '010', 'name': '冰棍', 'price': 4.5},
]
#存储营业额
transactions = []
while True:
menu()
choice = int(input("请选择你要进行的操作: "))
if choice == 1:
shops = add(shops)
elif choice == 2:
search(shops)
elif choice == 3:
shops = delete(shops)
elif choice == 4:
total_price = calculate(shops)
transactions.append(total_price)
elif choice == 5:
calculate_total(transactions)
elif choice == 0:
break
else:
print("输入有误!")
各个功能模块的代码,我这里没有贴上来,你可以去我的博客里面找下完整的代码和运行结果都有:
https://blog.csdn.net/c1007857613/article/details/131290534
//Product 类用于表示货品,包含编号、名称、单价等属性,同时提供添加、查询和删除货品等方法。
class Product:
def __init__(self, id, name, price):
self.id = id
self.name = name
self.price = price
def __str__(self):
return '{}\t{}\t{}'.format(self.id, self.name, self.price)
class ProductManager:
def __init__(self):
self.products = []
def add_product(self, product):
self.products.append(product)
def find_product_by_id(self, id):
for p in self.products:
if p.id == id:
return p
return None
def remove_product_by_id(self, id):
p = self.find_product_by_id(id)
if p:
self.products.remove(p)
//Transaction 类用于表示顾客的流水信息,包含流水编号、消费金额等属性。
class Transaction:
def __init__(self, id, total):
self.id = id
self.total = total
def __str__(self):
return '{}\t{}'.format(self.id, self.total)
//Supermarket 类用于管理超市的所有数据,包括货品和流水信息,提供添加、查询和删除货品,以及计算购物车总额、记录交易流水等方法。
class Supermarket:
def __init__(self):
self.product_manager = ProductManager()
self.transactions = []
self.current_id = 0
def add_product(self, id, name, price):
self.product_manager.add_product(Product(id, name, price))
def find_product_by_id(self, id):
return self.product_manager.find_product_by_id(id)
def remove_product_by_id(self, id):
self.product_manager.remove_product_by_id(id)
def calculate_total(self, cart):
total = 0
for item in cart:
p = self.find_product_by_id(item[0])
if p:
total += p.price * item[1]
return round(total, 1)
def add_transaction(self, total):
self.current_id += 1
t = Transaction(self.current_id, total)
self.transactions.append(t)
return t
def get_total_revenue(self):
return sum([t.total for t in self.transactions])
//主函数
def main():
s = Supermarket()
while True:
print('请选择操作:')
print('1. 添加货品')
print('2. 查询货品')
print('3. 删除货品')
print('4. 结算购物车')
print('5. 营业总额')
print('6. 退出')
choice = input('请选择操作编号:')
if choice == '1':
id = input('请输入货品编号:')
name = input('请输入货品名称:')
price = float(input('请输入货品单价(保留一位有效数字):'))
s.add_product(id, name, price)
elif choice == '2':
id = input('请输入货品编号:')
p = s.find_product_by_id(id)
if p:
print(p)
else:
print('货品不存在!')
elif choice == '3':
id = input('请输入货品编号:')
s.remove_product_by_id(id)
elif choice == '4':
cart = []
while True:
id = input('请输入货品编号(按回车结束):')
if not id:
break
p = s.find_product_by_id(id)
if p:
qty = int(input('请输入数量:'))
cart.append((id, qty))
else:
print('货品不存在!')
total = s.calculate_total(cart)
print('购物车总额为:{}'.format(total))
t = s.add_transaction(total)
print('交易流水为:{}'.format(t))
elif choice == '5':
revenue = s.get_total_revenue()
print('营业总额为:{}'.format(revenue))
elif choice == '6':
break
else:
print('输入有误,请重新输入!')
老板,觉得合适的话可以采纳。
# 定义货品信息列表,每个元素为一个字典,包含编号、名称和单价等信息
goods_list = [
{'id': '001', 'name': '面包', 'price': 9.9},
{'id': '002', 'name': '牛奶', 'price': 12.5},
{'id': '003', 'name': '饼干', 'price': 8.8},
# 可以继续添加更多货品信息
]
# 定义顾客流水信息列表,每个元素为一个字典,包含流水编号和消费金额等信息
flow_list = []
# 添加货品信息函数
def add_goods():
if len(goods_list) >= 100:
print("货品种类已达上限,无法添加!")
return
id = input("请输入货品编号:")
name = input("请输入货品名称:")
price = float(input("请输入货品单价:"))
goods = {'id': id, 'name': name, 'price': price}
goods_list.append(goods)
print("货品添加成功!")
# 查询货品信息函数
def query_goods():
id = input("请输入货品编号:")
for goods in goods_list:
if goods['id'] == id:
print("货品名称:", goods['name'])
print("货品单价:", goods['price'])
return
print("未找到该货品!")
# 删除货品信息函数
def delete_goods():
id = input("请输入货品编号:")
for goods in goods_list:
if goods['id'] == id:
goods_list.remove(goods)
print("货品删除成功!")
return
print("未找到该货品!")
# 输入购买信息函数
def input_purchase():
total_price = 0
while True:
id = input("请输入货品编号(输入0结束):")
if id == '0':
break
for goods in goods_list:
if goods['id'] == id:
count = int(input("请输入购买数量:"))
total_price += goods['price'] * count
break
else:
print("未找到该货品!")
print("结算总额为:", round(total_price, 1))
flow_list.append({'id': len(flow_list) + 1, 'price': total_price})
# 统计营业总额函数
def total_revenue():
total_price = 0
for flow in flow_list:
total_price += flow['price']
print("营业总额为:", round(total_price, 1))
# 主程序
while True:
print("欢迎使用超市自助结算系统!")
print("1. 添加货品信息")
print("2. 查询货品信息")
print("3. 删除货品信息")
print("4. 输入购买信息")
print("5. 统计营业总额")
print("0. 退出系统")
choice = input("请输入操作编号:")
if choice == '1':
add_goods()
elif choice == '2':
query_goods()
elif choice == '3':
delete_goods()
elif choice == '4':
input_purchase()
elif choice == '5':
total_revenue()
elif choice == '0':
print("感谢使用超市自助结算系统,再见!")
break
else:
print("输入有误,请重新输入!")
引用chatgpt:
class Goods:
def __init__(self, id, name, price):
self.id = id
self.name = name
self.price = price
class Customer:
def __init__(self, id, amount):
self.id = id
self.amount = amount
class Supermarket:
def __init__(self):
self.goods_list = []
self.customer_list = []
self.total_amount = 0
def add_goods(self, goods):
if len(self.goods_list) < 100:
self.goods_list.append(goods)
else:
print("货品种类上限已达100")
def remove_goods(self, id):
for goods in self.goods_list:
if goods.id == id:
self.goods_list.remove(goods)
break
else:
print("未找到该货品")
def add_customer(self, customer):
if len(self.customer_list) < 100:
self.customer_list.append(customer)
else:
print("顾客流水上限已达100")
def remove_customer(self, id):
for customer in self.customer_list:
if customer.id == id:
self.customer_list.remove(customer)
break
else:
print("未找到该顾客流水")
def calculate_total_amount(self):
for customer in self.customer_list:
for goods in self.goods_list:
if goods.id == customer.id:
self.total_amount += customer.amount * goods.price[1] + customer.amount * goods.price[2] + customer.amount * goods.price[3] + customer.amount * goods.price[4] + customer.amount * goods.price[5] + customer.amount * goods.price[6] + customer.amount * goods.price[7] + customer.amount * goods.price[8] + customer.amount * goods.price[9] + customer.amount * goods.price[10] + customer.amount * goods.price[11] + customer.amount * goods.price[12] + customer.amount * goods.price[13] + customer.amount * goods.price[14] + customer.amount * goods.price[15] + customer.amount * goods.price[16] + customer.amount * goods.price[17] + customer.amount * goods.price[18] + customer.amount * goods.price[19] + customer.amount * goods.price[20] + customer.amount * goods.price[21] + customer.amount * goods.price[22] + customer.amount * goods.price[23] + customer.amount * goods.price[24] + customer.amount * goods.price[25] + customer.amount * goods.price[26] + customer.amount * goods.price[27] + customer.amount * goods.price[28] + customer.amount * goods.price[29] + customer.amount * goods.price[30] + customer.amount * goods.price[31] + customer.amount * goods.price[32] + customer.amount * goods.price[33] + customer.amount * goods.price[34] + customer.amount * goods.price[35] + customer.amount * goods.price[36] + customer.amount * goods.price[37] + customer.amount * goods.price[38] + customer.amount * goods.price[39] + customer.amount * goods.price[40] + customer.amount * goods.price[41] + customer.amount * goods.price[42] + customer.amount * goods.price[43] + customer.amount * goods.price[44] + customer.amount * goods.price[45] + customer.amount * goods.price[46] + customer.amount * goods.price[47] + customer.amount * goods.price[48] + customer.amount * goods.price[49] + customer