购物车

Readme:

购物车程序:(by George.)

1、启动程序后,输入用户名密码后,如果是第一次登录,让用户输入工资,然后打印商品列表
2、允许用户根据商品编号购买商品
3、用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒 
4、可随时退出,退出时,打印已购买商品和余额
5、在用户使用过程中, 关键输出,如余额,商品已加入购物车等消息,需高亮显示
6、用户下一次登录后,输入用户名密码,直接回到上次的状态,即上次消费的余额什么的还是那些,再次登录可继续购买
7、允许查询之前的消费记录

几个关键的逻辑处理思路:

1.用户登录时查看:历史记录
2.用户退出时查看:本次购买记录、历史记录
  1.先将列表中临时信息append写入文件中;
  2.用户退出时打印列表信息;
  3.用户登录、退出时有选项可查看历史记录,此时打印文件信息;
3.余额修改
  1.登录时读取文件中余额;
  2.程序执行过程中完成扣款后将文件内容更新(新文件替换旧文件方式)
  3.程序退出时余额可直接从内存中读取

程序文件: 

user_passwd文件:

George 123
Tony 456
Julius 12345

balance文件:

Julius 900
Tony 500
George 681#每次用户完成购买后会出现在底部,因为操作文件是以.append方法实现,同时需要说明的是如果George用户未出现在该文件中,但在user_passwd文件中存在,在登录时会视为新可登录用户,则需要输入工资,下次则无需再次输入。

balance_tmp文件 :

Julius 900
Tony 500
George 681

commadity_price文件:

[("电视机_PANASONIC_55DR600C",9999),
("冰箱_SIEMENS_KA92NV41TI",10409),
("空调_HITACHI_C50FVY",6899),
("笔记本电脑_MAC_PRO250G",13000),
("热水壶_MIDEA_WFS5017TM",319),
("运动鞋_NICK_AIR",900),
("手机_MAC_IPHONE8X",6688)]

purchase_history文件:

('热水壶_MIDEA_WFS5017TM', 319)
|2017-12-25 17:10:08|Julius
('运动鞋_NICK_AIR', 900)
|2017-12-25 17:10:09|Julius
('热水壶_MIDEA_WFS5017TM', 319)
|2017-12-25 17:11:25|George
('热水壶_MIDEA_WFS5017TM', 319)
|2017-12-25 17:12:47|George
('热水壶_MIDEA_WFS5017TM', 319)
|2017-12-25 17:13:03|Tony
('热水壶_MIDEA_WFS5017TM', 319)
|2017-12-25 17:13:24|Tony
('热水壶_MIDEA_WFS5017TM', 319)
|2017-12-25 17:23:36|George

shopping.py文件(主程序):

# -*-coding:utf-8-*-
# _Author_:George
import os,sys,time

#用户名密码格式化字典
dict_user_pass = {}
#余额信息格式化字典
dict_balance = {}
#用户购买历史信息格式列表
list_pruchase_history = []

#用户登录欢迎信息
msg = '''
############################################
             欢迎登录 京东商城
############################################
登录用户:\033[34;1m%s\033[0m   您的余额:\033[34;1m%s\033[0m'''

#用户密码文件处理
def user_pass_info():
    with open("user_passwd.txt","r") as f1:
        for i in f1:
            line = i.strip()
            dict_user_pass[i.split(" ")[0]] = i.split(" ")[1]

# 余额文件处理
def balance_info():
    with open("balance.txt", "r", encoding="utf-8") as f3:
        for i in f3:
            if not i.startswith("\n"):
                line = i.strip()
                dict_balance[i.split(" ")[0]] = i.split(" ")[1]

#用户本次购买清单函数 (历史购买记录应该从文件里读,而不能从该列表中读)
def pruchase_history():
    print("\033[34;1m您的本次购物清单:\033[0m")
    for i in list_pruchase_history:
        print(i)

#####################################################################
#购买记录写入历史记录文件
def pruchase_his_wr_file():
    for i in list_pruchase_history:
        line = str(i).strip()
        with open("purchase_history.txt","a+",encoding="utf-8") as f:
            f.write(line+"\n")

#用户购买历史记录读取
def pruchase_his_ro_file():
    print("-----------------以下是历史记录-------------------")
    with open("purchase_history.txt", "r", encoding="utf-8") as f:
        for i in f:
            print(i.strip())
    print("-----------------以上是历史记录-------------------")

#余额信息改变后写入到文件
def balance_wr_file():
    balance_info()
    if login in dict_balance.keys():
        with open("balance.txt","r") as f1,open("balance_tmp.txt","w") as f2:
            for i in f1:
                if i.strip().split(" ")[0] == login or i.startswith("\n"):
                    continue
                f2.write(i)
        with open("balance_tmp.txt", "a+") as f3:
            balance = str(user_balance)
            f3.write("\n"+login +" "+balance.strip())
        # os.remove("balance.txt")
        # os.rename("balance_tmp.txt", "balance.txt")

#信息回写时文档格式化
        original = open("balance.txt","w")
        bala_tmp = open("balance_tmp.txt","r")
        lines = bala_tmp.readlines()
        for line in lines:
            if line.split():
                original.writelines(line)
            else:
                original.writelines("")
        original.close()
        bala_tmp.close()

#####################################################################
#主程序开始
user_pass_info()
count = 0
while count <3:
    login = input("Username:").strip()
    passwd = input("Password:").strip()
    count +=1

    if login not in dict_user_pass.keys() or passwd not in dict_user_pass[login]:
        print("\033[31;1mERROR! Invalid username or password!\033[0m")
    elif login in dict_user_pass.keys() and passwd in dict_user_pass[login]:
        while True:
            balance_info()
            if login in dict_balance.keys():
                user_balance = dict_balance[login]
                print(msg % (login, user_balance))
                while True:
                    print("\n序号---------商品名称------------商品价格")
                    with open("commodity_price.txt", "r", encoding="utf-8") as f3:
                        shopping_list = eval(f3.read())
                        for index, item in enumerate(shopping_list):
                            print(index, item)

                    user_choice = input("\n【\033[34;1m序号\033[0m】购买商品\n【\033[34;1mb\033[0m】退出\n【\033[34;1mh\033[0m】购买历史\n请输入您要的操作>>>").strip()
                    if user_choice == "b":
                        pruchase_history()
                        print("\033[34;1m您当前余额为:%s\033[0m" %user_balance)
                        exit()
                    if user_choice == "h":
                        pruchase_his_ro_file()
                    if user_choice.isdigit():
                        user_choice=int(user_choice)
                        if user_choice < len(shopping_list) and user_choice >=0:
                            p_item = shopping_list[user_choice]
                            p_item1_to_int = int(p_item[1])
                            user_balance = int(user_balance)

                            if p_item1_to_int <= user_balance:
                                list_pruchase_history.append(p_item)
                                list_pruchase_history.append("|"+ time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) + "|"+ login)
                                user_balance -= p_item1_to_int
                                print("\033[35;1m已完成扣款并添加【%s】至您的购物车\033[0m"%p_item[0])
                                print("\033[34;1m当前余额为:%s\033[0m" %user_balance)
                                pruchase_his_wr_file()
                                balance_wr_file()
                            else:
                                print("\033[35;1m您的余额不足,还是努力敲代码吧!\033[0m")

                        else:
                            error_input = input("Press '\033[31;1m[c]\033[0m' to continue>>:")
                            if error_input == 'c':
                                continue
                    else:
                        error_input = input("Press \033[31;1m[c]\033[0m to continue>>:")
                        if error_input == 'c':
                            continue
            else:
                first_logiGen_input = input("\n\033[35;1m>>>You are The first login<<<\033[0m \nEnter your salary first:")
                if first_logiGen_input != 0 or first_logiGen_input.isdigit():
                    add = (login+" "+first_logiGen_input)
                    with open("balance.txt","a+") as f:
                        f.write("\n"+ add)

 

posted on 2017-12-25 17:48  承祥君  阅读(353)  评论(2编辑  收藏  举报

导航