标签:size 整理 int password temp pass git sts 上层
模拟购物车的程序,是对之前学习的基础知识----字典、列表、文件的读写、字符的操作等知识的一次模拟练习,但在实际的编程中,将所有功能放在一个函数中实现,无疑减弱了程序的可读性和可维护性,购物车4引进了函数的概念,也将购物车需求经过整理如下:
要求
1、 登录功能
1> 登录验证:1、账户是否被锁定;2、验证用户为注册用户,登录密码是否正确,用户名与密码存放在文件中;
2> 验证失败三次,锁定账户,锁定账户在五分钟内不能再次登录,锁定账:
户存放在文件中。
2、 账户充值
1> 在购物时,出现余额不足是,可进行账户充值;
2> 可读取、保存账户余额。
3、 退出结算
1> 结束购物时,进行购物结算,打印消费信息与账户余额;
2> 购物结束时,保存购物商品信息;
3> 购物结束时,保存账户余额。
4、 购物
1> 打印操作说明;
2> 打印商品列表;
3> 商品分类;
4> 余额不足提示。
5> 购物操作,可根据不同购物类型,选择,显示该类型下商品列表,可选择返回上层目录。
实现代码如下:
def readDirInfo(filename): ‘读取字典列表,依据传递的文件名,获取不同的字典信息‘ nameList = ‘‘ with open(filename, ‘a+‘, encoding=‘utf8‘) as f: f.seek(0) nameList = str(f.readlines()) nameList = nameList.strip(‘]‘).strip(‘[‘) nameList = nameList.strip(‘\"‘).strip(‘\"‘) if len(nameList) == 0: return {} return eval(nameList) #字符转字典 def login(iTime = 3): ‘用户登录操作,包括以下功能:1、判断是否为注册账户; 2、登录账户是否被锁定(注:默认输错用户名密码三次后,锁定账号,五分钟内不能登录)‘ i = 1 flag = False lock_namelist = readDirInfo(‘locklist.txt‘) while i <= iTime: username = input("username:") password = input("password:") if loginLock(username,lock_namelist): print("you username is locked, try again after 5 min") break elif logincheck(username,password): print("welecom to shopping maket") flag = True break elif i == iTime: print("input more than three times, try again after 5 min") addLockDir(username, lock_namelist) break else: print("you put an wrong name or password,please input again") i += 1 return flag,username def loginLock(name, lock_namelist): ‘判断登录账号是否被锁定,如果被锁定时间超过5分钟,允许用户再次登录‘ flag = False if name in lock_namelist: last_time = datetime.datetime.strptime(lock_namelist[name], "%Y-%m-%d %H:%M:%S") now_time = datetime.datetime.now() minute = (now_time - last_time) if int(minute.seconds/60) <= 5: flag = True return flag def logincheck(name,password): ‘是否为注册账号‘ flag = False name_dir = readDirInfo(‘name.txt‘) if name in name_dir: if password == name_dir[name]: flag = True return flag def addLockDir(name,lock_namelist): ‘字典中添加元素,如果元素存在,修改元素的值‘ if name in lock_namelist: lock_namelist[name] = datetime.datetime.now().strftime( "%Y-%m-%d %H:%M:%S") else: lock_namelist[name] = datetime.datetime.now().strftime( "%Y-%m-%d %H:%M:%S") with open(‘locklist.txt‘, ‘w‘, encoding="utf8") as f_read: f_read.write(str(lock_namelist)) def PrintOper(): ‘打印操作说明‘ prolist = ‘‘‘ *************** 系统操作说明 **************** q : 退出系统 c : 账号充值 h : 购物记录 l : 商品列表 ************************************************ ‘‘‘ print(prolist) def CreateDir(): ‘判断文件夹是否存在,如果存在则退出,如果不存在,创建文件夹‘ isExists = os.path.exists(‘History‘) if not isExists: os.mkdir(‘History‘) return isExists def Exit(): ‘退出购物系统,退出时进行购物结算‘ Account() saveLevelMoney() exit() def saveLevelMoney(): with open(‘remain.txt‘,‘w‘,encoding=‘utf8‘) as f: f.write(str(remain_dir)) def Account(): ‘购物计算,将购物信息写入购物历史文件中‘ if len(shopping_cart) == 0: return False print("\033[34;1m---------------product list-----------------\033[0m \n \033[42;1m") temp = ‘id product number pric Totalpric‘ print(temp) index = 1 total_mon = 0 f = open("product.txt", "a+", encoding="utf8") now_time = datetime.datetime.now().strftime(‘[%Y-%m-%d %H:%M:%S]‘) f.write(now_time + ‘\n‘ + temp + ‘\n‘) temp = ‘‘ for i in shopping_cart.keys(): total_mon += shopping_cart[i][1] * shopping_cart[i][0] temp = str("%d %10s %7d %7d %7d \n" % (index, i, shopping_cart[i][1], shopping_cart[i][0], shopping_cart[i][1] * shopping_cart[i][0])) print(temp) f.write(temp) index += 1 f.close() print("you pay money is:%d \n you level money is: %d \n" % (total_mon, remain_dir[name])) print("\033[0m \n \033[34;1m-------------end-------------\033[0m") def Recharge(): ‘账号充值操作‘ while True: temp = input("Please rechange money:") if temp.isdigit(): if name in remain_dir: remain_dir[name] += int(temp) else: remain_dir[name] = int(temp) break print("you input a unknow number,please check it and input again!") def History(): ‘打印历史购物记录‘ filename = ‘History\\‘ + name + ‘.txt‘ filename = filename.rstrip("\\") print(filename) if os.path.exists(filename): with open(filename,‘r‘,encoding=‘utf8‘) as f: for line in f: print(line.strip(‘\n‘)) else: print(‘No you shoppong history‘) def Operation(): ‘用户交互操作‘ while True: PrintOper() oper = str(input("Please input you choice:")).strip() if oper == ‘l‘: print(‘欢迎进入购物中心‘) shopping(product_list) elif oper in Oper_dir: Oper_dir[oper]() else: print("You input no in Oper list!") continue def ProductList(print_list): ‘打印商品列表‘ if isinstance(print_list, dict): # 是否为列表 for key in print_list: print(key) else: index = 0 for product in print_list: print(index, product) index += 1 print(‘b:‘,‘返回上级菜单‘) print(‘q:‘,‘退出购物中心‘) print(‘c‘,‘充值‘) def shopping(product_list): ‘购物操作‘ current_layer = product_list while True: ProductList(current_layer) choice = input(">>:").strip() if len(choice) == 0: continue if choice.isdigit(): choice = int(choice) if choice >= 0 and choice < len(current_layer): product = current_layer[choice] if product[1] <= remain_dir[name]: if product[0] in shopping_cart: shopping_cart[product[0]][1] += 1 else: shopping_cart[product[0]] = [product[1], 1] remain_dir[name] -= product[1] print("\033[42;1mAdded product: %s into shoing cart ,you current balance %s \033[0m" % (product[0], str(remain_dir[name]))) else: print("\033[42;1m [warning] you balance is no enough\033[0m, product:" + str( product[1]) + " short for " + str(product[1] - remain_dir[name])) else: print("\033[41;1mYou choice product is no in product_list\033[0m") elif choice in current_layer: if isinstance(current_layer, dict): # 是否为列表 last_layer.append(current_layer) current_layer = current_layer[choice] elif choice == ‘q‘: break elif choice == ‘b‘: current_layer = BackUpLevel(current_layer) elif choice == ‘c‘: Recharge(name) def BackUpLevel(current_layer): ‘返回到商品列表上一层‘ if last_layer: current_layer = last_layer[-1] last_layer.pop() return current_layer import datetime import os product_list = {"生活用品":[[‘毛巾‘,20], [‘洗衣液‘,80], [‘衣架‘, 10], [‘洗衣粉‘,60], [‘洗发水‘, 80], [‘厕洗剂‘,50]], "家电":[[‘电视机‘,5000], [‘电饭煲‘,300], [‘电磁炉‘,200], [‘高压锅‘,800], [‘电饼铛‘,200]], } shopping_cart = {} Oper_dir = {‘q‘:Exit,‘c‘:Recharge,‘h‘:History} last_layer = [ product_list ] remain_dir = readDirInfo(‘remain.txt‘) flag,name = login() if flag: Operation()
标签:size 整理 int password temp pass git sts 上层
原文地址:http://www.cnblogs.com/maoxiong1985/p/7976764.html