一、知识点
1、字典
嵌套字典
2、列表
3、文件操作
打开文件的模式有:
◾r,只读模式(默认)。
◾w,只写模式。【不可读;不存在则创建;存在则删除内容;】
◾a,追加模式。【可读; 不存在则创建;存在则只追加内容;】
"+" 表示可以同时读写某个文件
◾r+,可读写文件。【可读;可写;可追加】
◾w+,写读
◾a+,同a
"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)
◾rU
◾r+U
"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)
◾rb
◾wb
◾ab
4、函数
定义 def 函数名():
二、作业
1、启动程序后,输入用户名密码后,如果是第一次登录,让用户输入工资,然后打印商品列表
2、允许用户根据商品编号购买商品
3、用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
4、可随时退出,退出时,打印已购买商品和余额
5、在用户使用过程中, 关键输出,如余额,商品已加入购物车等消息,需高亮显示
6、用户下一次登录后,输入用户名密码,直接回到上次的状态,即上次消费的余额什么的还是那些,再次登录可继续购买
7、允许查询之前的消费记录
流程图:
#Author xq import pickle def pickle_load(filename): with open(filename,'rb') as input: try: return pickle.load(input) except EOFError: return None def pickle_dump(dict,filename): with open(filename,'wb') as output: try: return pickle.dump(dict,output) except EOFError: return None product_list=[('ipad',6800),('phone',5200),('computer',4000),('book oracle',70),('glass',30),('hat',60)] userInfo=pickle_load('../db/userInfo') while not userInfo: userInfo={} break username=input("请输入用户名:") while True: pwd=input("请输入密码:") if username in userInfo : if pwd == userInfo[username]["pwd"]: print("登录成功") shopping_list= userInfo[username]["shopping_list"] #调用函数打印已购商品及余额 print("您之前的消费情况如下:".center(80,'*')) print("\033[31;1m已购买的商品是\033[0m%s" % userInfo[username]["shopping_list"]) print("余额是\033[31;1m%s\033[0m" % userInfo[username]["salary"]) break else: continue else : while 1: salary=input("请输入工资:") if salary.isdigit(): salary=int(salary) break else: continue userInfo.setdefault(username,{"pwd": pwd, "salary": salary, "shopping_list": []}) shopping_list= userInfo[username]["shopping_list"] print("打印当前用户工资额:", userInfo[username]["salary"]) break while True: for index, item in enumerate(product_list): print(index,item) user_choice=input("商品编号:购买;q:退出;c:查询消费记录;请选择:") 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] if p_item[1] <= userInfo[username]["salary"]: #userInfo[username]["shopping_list"]= p_item shopping_list.append(p_item) userInfo[username]["salary"] -= p_item[1] print("商品%s已加入到您的购物车,您的当前余额是:\033[31;1m%s\033[0m"% (p_item, userInfo[username]["salary"])) continue else: print("\033[41;1m你的余额只有[%s]啦,请重新购买,\033[0m"% userInfo[username]["salary"]) continue else: print("product code [%s] is not exist"% user_choice) continue elif user_choice == 'c': print("\033[31;1m已购买的商品是\033[0m%s"% userInfo[username]["shopping_list"]) print("余额是\033[31;1m%s\033[0m"% userInfo[username]["salary"]) elif user_choice == 'q': print('shopping list'.center(60,'-')) #for p in shopping_list : # print(p) print(shopping_list) userInfo[username]["shopping_list"] = shopping_list print("您的当前余额是\033[31;1m%s\033[0m:"% userInfo[username]["salary"]) break else: print("invalid option") continue pickle_dump(userInfo,'../db/userInfo')