代码如下: #模拟购物车 #功能简介: # 1 添加商品,可以设置商品的数目 # 2 删除商品,可以减少商品数目 # 3 允许清空购物车 # 4 可以统计商品的总金额、 #购物车 shoppingCart={} #仓库{id,name,price,num} shopStore={1:{'id': 1, 'name': '苹果', 'price': 2, 'num': 3},2: {'id': 2, 'name': '烧鸡', 'price': 1, 'num': 23}, 3: {'id': 3, 'name': '肉', 'price': 2, 'num': 33},4: {'id': 4, 'name': '豆腐', 'price': 4, 'num': 19}} #计算总价 def totalCost(): global shoppingCart#声明全局变量 sumCost=0#总消费 for k,v in shoppingCart.items(): sumCost+=v['price']*v['num']#单价*数目 return sumCost def addFGoods(id,name,price,num): global shoppingCart # 声明全局变量 if id not in shoppingCart: shoppingCart[id]={'id':id,'name':name,'price':price, 'num':num} else: shoppingCart[id]['num']+=num print(totalCost()) print(shoppingCart) def delGoods(id,num): global shoppingCart # 声明全局变量 if id not in shoppingCart: return False elif shoppingCart[id]['num']>num: shoppingCart[id]['num']-=num else: shoppingCart.pop(id) print(totalCost()) print(shoppingCart) def clearCart(): global shoppingCart # 声明全局变量 shoppingCart.clear() print(shoppingCart) if __name__=='__main__': while True: id=int(input('Please input id')) num=int(input('please input num ')) if id not in shopStore: print("id is not in ") i = int(input('如果想更改订单,请输入1,退出输入2,清空购物车输入0,继续购物请输入3')) if i == 1: id = int(input('Please input id')) num = int(input('please input num ')) delGoods(id, num) elif i == 2: break elif i == 0: clearCart() else: continue elif shopStore[id]['num']>num: shopStore[id]['num']-=num addFGoods(id,shopStore[id]['name'],shopStore[id]['price'],num) print('已经加了购物车') i=int(input('如果想更改订单,请输入1,退出输入2,清空购物车输入0,继续购物请输入3')) if i==1: id = int(input('Please input id')) num = int(input('please input num ')) delGoods(id,num) elif i==2: break elif i==0: clearCart() else: continue else: print("缺货") i = int(input('如果想更改订单,请输入1,退出输入2,清空购物车输入0,继续购物请输入3')) if i == 1: id = int(input('Please input id')) num = int(input('please input num ')) delGoods(id, num) elif i == 2: break elif i == 0: clearCart() else: continue print('欢迎购物') 运行结果: