标签:with 存在 append 商品 split readlines choice product 过程
购物车程序作业需求:
1、启动程序后,输入用户名密码后,如果是第一次登录,让用户输入工资,然后打印商品列表
2、允许用户根据商品编号购买商品
3、用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
4、可随时退出,退出时,打印已购买商品和余额
5、在用户使用过程中, 关键输出,如余额,商品已加入购物车等消息,需高亮显示
6、用户下一次登录后,输入用户名密码,直接回到上次的状态,即上次消费的余额什么的还是那些,再次登录可继续购买
7、允许查询之前的消费记录
代码如下:
# Author:pengp #!/usr/bin/env python # -*- coding: utf-8 -*- with open("user_shopping","r",encoding="utf-8") as f: yj = eval(f.read()) while True: username = input("请输入用户名: \033[0m") passwd = input("请输入密码: \033[0m") if username == yj["name"] and passwd == yj["passwd"]: print("您的资金余额为:\033[1;31;0m%s\033[0m"%(yj["salary"])) else: print("用户名或密码错误") exit() while True: pay = input("请问要充值吗? (y/n):") if pay == "y": pay_rmb = input("请输入需要充值的金额: ") salary_new = yj["salary"] + int(pay_rmb) yj["salary"] = salary_new # yj_pay_salary = (yj["salary"]) print("现在余额为\033[1;31;0m%d\033[0m" %(yj["salary"])) with open("user_shopping","w",encoding="utf-8") as ff: ff.write(str(yj)) elif pay == "n": f = open(‘product_list‘, ‘r‘) product_list = f.readlines() while True: print("product_list".center(50, ‘-‘)) for index,item in enumerate(product_list): item = item.split() print(index,item) user_choice = input("请选择购买商品编码,退出请按e: ") 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].split() if int(p_item[1])<yj["salary"]: salary_banance = yj["salary"] - int(p_item[1]) yj["salary"] = salary_banance yj["shopping_list"].append(p_item) with open("user_shopping","w",encoding="utf-8") as f_new: f_new.write(str(yj)) print("商品%s已购买"%p_item) else: print("余额不足,请先充值") break else: print("商品编号%s不存在,请重新输入:"%user_choice) continue elif user_choice == ‘e‘: print(‘shopping_list‘.center(50,‘-‘)) for index,p in enumerate(yj["shopping_list"]): print(index,p) exit("您的余额为:%s,欢迎下次光临" % (yj["salary"]))
标签:with 存在 append 商品 split readlines choice product 过程
原文地址:http://www.cnblogs.com/pengp/p/6850147.html