##### Author:yyw, created on 20180509 ##### ''' 0. Define functions - prt_all_prod(prod_dict) - get_price_by_index(prod_dict, _index) - get_sku_by_index - valid_cus_name - get_balance_by_name - upd_balance_by_name(filename,name,balance) 1. Get customer name; 2. Print shopping list; 3. Loop: input index and get price summary, break by press 'q'; 4. Write shopping transaction to transaction file, and update balance in balance file ''' import json import time def prt_all_prod(prod_dict): for index,i in enumerate(prod_dict): print(index,i,prod_dict[i]) return def get_price_by_index(prod_dict, _index): for index,i in enumerate(prod_dict): while index ==_index: _price = prod_dict[i] break return _price def get_sku_by_index(prod_dict, _index): for index,i in enumerate(prod_dict): while index ==_index: _sku = i break return _sku def valid_cus_name(name_list,cus_name): result = name_list.get(cus_name, "NO") return result def get_balance_by_name(name_list,_cus_name): balance = name_list.get(_cus_name) return balance def upd_balance_by_name(filename, _name,balance): with open(filename, "r") as fr: info2 = json.loads(fr.read()) info2[_name] = balance # print(info2) with open(filename, "w") as f: f.write(json.dumps(info2)) return 0 ### 1.Print shopping list; with open("sku","r") as f: sku_list = json.loads(f.read()) #print(data) ### 2. Get customer name; print("------开始校验姓名------") with open("balance","r") as f: name_list = json.loads(f.read()) print(name_list) _name = input("请输入您的姓名》》》:") while valid_cus_name(name_list,_name) =="NO" : _name = input("输入的姓名不是金卡会员,请再次输入您的姓名》》》:") if _name == 'q': print("@@@@用户要求退出程序!!!") break _bal = get_balance_by_name(name_list,_name) print(" ##### 欢迎 %s 来到星空购物广场 ##### "%_name) print(" ##### 您的账号余额还有 %s 元,不过您可以透支消费,##### "%_bal) print("-------------商品列表-------------") prt_all_prod(sku_list) #print(get_sku_by_index(sku_list,0)) #print(get_price_by_index(sku_list,0)) _shopping_cart =[] _summary = 0 _count = 0 _time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) while True: _choice = input("请输入您想购买的商品编号,或者按 'q' 退出》》》:") if _choice.isdigit(): _choice = int(_choice) if _choice < len(sku_list) and _choice >= 0: # 判读list范围 p_price = get_price_by_index(sku_list,_choice) p_sku = get_sku_by_index(sku_list,_choice) ### 添加记录到shop,列表 _shopping_cart.append([p_sku,p_price]) _summary = _summary+p_price _count = _count+1 print("加入 33[31;1m%s 33[0m 到购物车! 花了 33[31;1m%s 33[0m 元, 总计消费了 33[31;1m%s 33[0m 元" %(p_sku,p_price,_summary)) else: print("商品 %s 不存在!!" % (_choice)) elif _choice == 'q': with open("shopping_trx", "a", encoding="UTF-8") as f_trx: print(" ------shopping list---------") for p in _shopping_cart: f_trx.writelines(_time+" "+_name+" "+p[0]+" "+str(p[1])+" ") ####list如果转化为str print(p) print("