标签:信息 选择 for while 入门 pre 列表 键盘 判断
选择商品,结算所选的商品
#目前总资产 asset_all = 0 #所选商品总价 all_price = 0 #购物车列表,目前已选择商品 #每个元素的结构:"商品名":{‘price‘:"单个商品价格",‘num‘:"购买数量"} car_dict = {} i1 = input("请输入总资产:") asset_all += int(i1) goods = [ {"name":"电脑","price":1999}, {"name":"鼠标","price":50}, {"name":"键盘","price":40}, {"name":"U盘","price":20} ] #循环输出商品信息 for k,i in enumerate(goods,1): print(k,i[‘name‘],i[‘price‘]) #选择商品将其加入购物车 while True: i2 = input("请选择商品(q结算):") if i2.lower() == ‘q‘: break i2 -= 1 name = goods[i2]["name"] price = goods[i2]["price"] if name in car_dict.keys(): car_dict[name]["num"] += 1 else: car_dict[name] = {"price":price,"num":1} #计算购物车里所有商品的总价格 for i,j in car_dict.items(): p = j["price"] n = j["num"] all_sum = p * n all_price += all_sum #判断是否能购买商品 if all_price > asset_all: print("余额不足,请充值") else: asset_all -= all_price print("购买成功") car_dict.clear()
标签:信息 选择 for while 入门 pre 列表 键盘 判断
原文地址:https://www.cnblogs.com/chy-op/p/9864019.html