1.用户接口
>>>判断用户工资是否有记录
>>>能够从文件中读取商品列表
>>>能够选择想要的商品,并扣除工资
>>>打印并保存订单信息以及工资余额
2.商家接口
>>>能够读取商品列表
>>>能够修改商品价格并保存
>>>能够添加商品并保存
>>>能够删除商品并保存
3.代码实现
shopping_cart.py
'''实现购物城功能---文件操作版''' # 接口 cart_user 和 cart_merchant role = input('请输入你要进入的角色接口(user/merchant)') if role == 'user': from day2 import cart_user elif role == 'merchant': from day2 import cart_merchant else: print("你输入的角色接口有误!")
cart_user.py
'''实现购物车功能 --- 用户接口''' # 获得商品列表 def get_product(): product_list = [] with open('product.txt', 'r') as f: for i in f.readlines(): i = i.replace(' ', '') product_list.append(i.split(':')) return product_list # 保存商品列单及余额 def save_product(goods_order_salary): with open('shopping.txt', 'a') as f: f.write(goods_order_salary + ' ') # 读取工资 def read_salary(): with open('shopping.txt', 'r') as f: data = f.read() return data # 判断 salary 是否有记录 data = read_salary() if 'balance' in data: salary = data.split(':')[-1] print('您目前的余额为:'+salary) else: salary = input("请输入你的工资:") # 主程序 shopping_list = [] # if salary.isdigit(): salary = int(salary) while True: product_list = get_product() for index, item in enumerate(product_list): print(index, item) user_choice = input('选择你想要的产品:') if user_choice.isdigit(): user_choice = int(user_choice) if user_choice < len(product_list) and user_choice >= 0: p_item = product_list[user_choice] p_item[1] = int(p_item[1]) if p_item[1] <= salary: shopping_list.append(p_item) salary -= p_item[1] print('Added %s into shopping cart.your present balance is 33[31;1m%s 33[0m' % (p_item, salary)) save_product(str(p_item)) else: print('