Welcome!!!

F

伞兵一号,申请出战

购物系统编写

购物系统编写

项目结构

bin目录

  1. start.py(启动文件,串联所有功能)

    import sys,os
    my_path = os.getcwd()
    sys.path.append(os.path.join(my_path,'..','core'))
    import login,register,add_shop_car,settlement
    
    dict1 = {
        '1':'\t登录',
        '2':'\t注册',
        'q':'\t退出'
    }
    dict2 = {
        '1':'\t购物',
        '2':'\t结算',
        'q':'\t退出'
    }
    
    while True:
        # 输出指令字典
        for i in dict1:
            print(i, dict1[i])
        choise = input('请输入指令>>>').strip()
        if choise == 'q':
            break
        elif choise == '1':
            username = login.login()
            if len(username) == 0:
                continue
            else:
                while True:
                    # 输出指令字典
                    for i in dict2:
                        print(i, dict2[i])
                    choise = input('请输入指令>>>').strip()
                    if choise == 'q':
                        break
                    elif choise == '1':
                        add_shop_car.addShopCar(username)
                    elif choise == '2':
                        settlement.settlement(username)
                    else:
                        print('命令有误,请重试')
        elif choise == '2':
            register.register()
        else:
            print('命令有误,请重试')
    

core目录

  1. login.py(登录功能)

    # 登录功能
    import os,sys
    my_path = os.getcwd()
    sys.path.append(os.path.join(my_path,"..",'lib'))
    import user_data
    def login():
        username = input('请输入用户名>>>').strip()
        password = input('请输入密码>>>').strip()
        user_info = user_data.getUser(username)
        if user_info == 0:
            print('用户名不存在')
            return False
        elif user_info['password'] == password:
            print(f'{username},登陆成功')
            return username
        else:
            print('密码错误')
            return False
    
    
  2. register.py(注册功能)

    # 注册功能
    import user_data
    def register():
        username = input('请输入一个用户名>>>').strip()
        # 查重
        if len(user_data.getUser(username)) == 0:
            password = input('请输入密码>>>').strip()
            dict_user = {"username":username,"password":password,"balance":15000,"shop_car":{}}
            user_data.create(dict_user)
            print(f'{username},注册成功')
            return True
        else:
            print(f'{username}已存在')
            return False
    
  3. add_shop_car.py(选购功能,商品添加到购物车)

    # 添加商品到购物车
    import user_data
    def addShopCar(username):
        shop_list = [
            ['挂壁面', 3],
            ['印度飞饼', 22],
            ['极品木瓜', 666],
            ['土耳其土豆', 999],
            ['伊拉克拌面', 1000],
            ['董卓戏张飞公仔', 2000],
            ['仿真玩偶', 10000]
        ]
        # 创建购物车容器{'商品':['单价',数量]}
        shop_car = {}
        num = 0
        tag_list = {'tag1': True, 'tag2': True,'tag3':True}
        while tag_list['tag1']:
            for i in shop_list:
                print(f'商品编号:{num}\t商品名称:{i[0]}\t商品单价:{i[1]}元')
                num += 1
            choise = input('请输入想要购买的商品序号,输入q退出>>>').strip()
            if choise == 'q':
                tag_list['tag1'] = False
            elif not choise.isdigit():
                print('请输入正确的商品编号')
            elif int(choise) < 0 and int(choise) > len(shop_list):
                print('商品不存在')
            else:
                while tag_list['tag2']:
                    shop_number = input('请输入想要购买的数量,输入q退出>>>').strip()
                    if shop_number == 'q':
                        tag_list['tag2'] = False
                    elif not shop_number.isdigit():
                        print('请输入正确的数量')
                    elif int(shop_number) < 0:
                        print('请输入正确的数量')
                    else:
                        shop_item = {shop_list[int(choise)][0]:[shop_list[int(choise)][1],int(shop_number)]}
                        while tag_list['tag3']:
                            chiose_sure = input(f'确认添加购物车{shop_list[int(choise)][0]},单价{shop_list[int(choise)][1]}元,数量{shop_number}个,y/n?')
                            if chiose_sure == 'y':
                                shop_car.update(shop_item)
                                user_info = user_data.getUser(username)  # 取出用户信息
                                shop_car_dict = user_info['shop_car']  # 取出原有购物车数据
                                shop_car_dict.update(shop_car)  # 合并购物车数据
                                user_info['shop_car'] = shop_car_dict  # 新的购物车数据替换老的
                                user_data.createUser(user_info)  # 重新写入用户信息
                                tag_list['tag2'] = False
                                tag_list['tag3'] = False
                            elif chiose_sure == 'n':
                                tag_list['tag3'] = False
                            else:
                                print('命令错误')
    
  4. settlement.py(结算功能)

    # 结算功能
    import user_data
    def settlement(username):
        # 算出总金额
        acount = 0
        user_info = user_data.getUser(username)  # 用户信息
        shop_car = user_info['shop_car']
        while True:
            for i in shop_car.values():
                acount += int(i[0])*int(i[1])  # 获取待支付金额
            choise = input(f'当前账户余额{user_info["balance"]},待支付{acount},是否支付y/n?')
            if choise == 'y':
                balance = int(user_info["balance"]) - int(acount)
                if balance >= 0:
                    user_info['balance'] = balance
                    user_info['shop_car'] = {}
                    user_data.createUser(user_info)
                    print(f'支付成功,当前余额{balance}元')
                    return
                else:
                    print('余额不足,请充值')
                    return
            elif choise =='n':
                return
            else:
                print('命令错误')
    

lib目录

  1. user_data.py(公共功能,读写文件操作)

    import json,os
    
    my_path = os.path.dirname(__file__)
    # 取用户信息,反序列化后输出
    def getUser(username):
        try:
            with open(fr'{my_path}\..\db\{username}.txt', 'r', encoding='utf8') as f:
                res = f.read()
                user_info = json.loads(res)
            return user_info
        except FileNotFoundError:
            return 0
    
    
    # 注册,修改用户
    def createUser(user_dict):
        username = user_dict['username']
        with open(fr'{my_path}\..\db\{username}.txt', 'w', encoding='utf8') as f1:
            res = json.dump(user_dict,f1)
    

编写思路

  1. 分析数据存储模式
    1. 数据以文件形式存储,所以创建db文件,内部存放txt类型数据文件
    2. 数据格式和需要的内容,需要以json格式存储,例:{"username": "oscar", "password": "oscar123", "balance": 14934, "shop_car":
  2. 分析需求
    1. 需要用到大量的读写操作,可以定义成公共功能模块供调用
    2. 需要登录,注册,选购,结算四个主要功能
posted @ 2022-03-31 21:57  程序猿伞兵一号  阅读(40)  评论(0)    收藏  举报