Python购物车系统

'''用户名和密码存放于文件中,格式为:name|password

启动程序后,先登录,登录成功则让用户输入工资,然后打印商品列表,失败则重新登录

允许用户根据商品编号购买商品

用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒

可随时退出,退出时,打印已购买商品和余额

余额:注册时默认每个用户拥有20000

退出登录,退出后可注册,并重新登录
'''

# 大部分用户输入的情况都考虑到了,基本不会出现bug,功能也应该较为完整


user = {"name":None,'money':None}
money_start = [0]
buy_list = {}
count_money = [0]

def register_check(name):
    ''' 判断用户名是否被注册'''
    with open('users.txt', 'r', encoding='utf8') as f:
        data = f.read()
        data = data.split("|")
    for i in data:
        user_info = i.split(':')
        username = user_info[0]
        if username == name:
            return 0


def get_goods():
    ''' 获取文件中货物并打印成列表'''
    with open('goods.txt', 'r', encoding='utf8') as fr:
        goods_list = fr.read()
        goods_list = eval(goods_list)

        return goods_list
goods_list = get_goods()

def get_money(name):
    ''' 根据用户名从文件中获取钱数'''
    money = 0
    with open('money.txt', 'r',encoding='utf8') as fr:
        data = fr.read()
        data = data.split('|')
        # 判断是否已有用户名
        for i in data:
            money_info = i.split(':')
            if name == money_info[0]:
                money = money_info[1]
        return money


def money_in(money):
    ''' 将购买后剩下的钱放回文件中'''
    import os
    with open('money.txt', 'r', encoding='utf8') as fr,\
        open('money1.txt',  'w', encoding='utf8') as fw:
            data = fr.read()
            data = data.replace(f'{user["name"]}:{money_start[0]}', f'{user["name"]}:{money}')
            fw.write(data)
    os.remove('money.txt')
    os.rename('money1.txt', 'money.txt')

def auto(func):
    def wrapper(*args,**kwargs):
        if user['name']:
            return func(*args,**kwargs)
        else:
            return login()
    return wrapper

def login():
    ''' 登录系统'''
    while True:
        name = input("请输入用户名:").strip()
        pwd = input("请输入密码:").strip()
        inp_user_info = f'{name}:{pwd}'    # 将用户名和密码合并成存储的格式,方便比较
        with open('users.txt', 'r', encoding='utf8') as f,\
            open('money.txt', 'r', encoding='utf8') as fr:
                user_info = f.read()
                money_info = fr.read()
        user_info = user_info.split('|')
        money_info = money_info.split('|')

        if inp_user_info in user_info:
            print('登录成功')
            user["name"] = name
            for i in money_info:
                money = i.split(':')
                if name == money[0]:
                    user["money"] = money[1]
                    money_start[0] = money[1]
                    break
            break
        else:
            print("用户名或密码错误")


def register():
    ''' 注册系统'''
    while True:
        name=input("请输入用户名:").strip()
        if register_check(name) == 0:
            print('该用户名已被注册')
            break
        if not user['name']:
            pwd=input("请输入密码:").strip()
            re_pwd=input("请重复输入密码:").strip()
            if pwd==re_pwd:
                with open("users.txt", mode="a", encoding="utf8") as f,\
                     open('money.txt', mode='a', encoding='utf8') as fr:
                        data=f"{name}:{pwd}|"
                        data1 = f'{name}:{20000}|'
                        f.write(data)
                        fr.write(data1)
                print("注册成功")
                break
            else:
                print("两次输入的密码不一致")
        else:
            print('已经登录,无法注册!')
            break
@auto
def shopping():
    ''' 购物系统'''
    money = 0
    while True:
        for i, k in enumerate(goods_list):
            print(i, ":", k)
        choose = input("请输入你要购买的商品序号(输入q退出):").strip()
        
        if choose.isdigit():    # 判断用户输入是否为数字
            choose = int(choose)            
            if choose < len(goods_list):    # 判断用户输入是否超过列表
                goods_name = goods_list[choose][0]
                goods_price = goods_list[choose][1]
                if goods_name in buy_list:
                    buy_list[goods_name]["count"] += 1
                else:
                    buy_list[goods_name]={'price' : goods_price, 'count': 1}
                    money += goods_price
                    count_money[0] = money
                    print("你购买的商品有:", buy_list)
            else:
                print("你输入的商品不存在")
        elif choose == 'q':
            print(f"你购买的商品有:{buy_list},总价为{money}")
            break
        else:
            print("请输入正确的商品编号")

@auto
def shopping_car():
    ''' 购物车'''
    while True:
        print(f'购物车商品:{buy_list},总价为{count_money}')

        goods_choice = input('请问需要删除哪个商品,不需要删除请按q退出')
        if goods_choice == 'q':
            break
        if goods_choice not in buy_list:
            print('输入商品错误')
            continue
        print(buy_list[goods_choice])
        buy_list[goods_choice]["count"] -= 1

        # 减掉价格
        for goods in goods_list:
            if goods_choice in goods:
                count_money[0] -= goods[1]

@auto
def pay():
    ''' 支付系统'''
    print(f'购物车商品:{buy_list}, 总价:{count_money[0]},您的余额为{user["money"]}')
    while True:
        choice = input('是否需要支付(Y/y),不支付会清空购物车(N/n):')
        if choice == 'Y' or choice == 'y':
            money = int(user['money'])-int(count_money[0])
            if money < 0:
                print('您的余额不足,请减少购物车商品!')
                break
            else:
                user['money'] = money
                print(f'支付{count_money[0]}成功,已成功购买{buy_list},余额为{money}')
                money_in(money)
                break
        # 清空购物车
        elif choice == 'N' or choice == 'n':
            buy_list.clear()
            count_money[0] = 0
            print('清空购物车成功,欢迎下次光临')
            break
        else:
            print('请按照要求输入!')

@auto
def count():
    ''' 显示余额'''
    print(f'你的余额为:{user["money"]}')


def login_out():
    '''退出登录'''
    
    # 判断是否已经登录
    global user
    if not user["name"]:
        print('请先登录')
        return  
    
    choice = input("是否退出登录(Y/y)")
    if choice == 'Y' or choice == 'y':
        user = {"name": None, 'money': None}
        print(user)
        print('您已退出登录')


func_dic = {"1": login, "2": register, "3": shopping, "4": shopping_car, "5": pay, "6": count, "7": login_out}
while True:
    print('''
    1:登陆
    2:注册
    3:购物
    4:购物车
    5:结账
    6:余额
    7:退出登录
    8:退出
    ''')
    choice=input("请输入你想进行的步骤:").strip()
    if choice in func_dic :
        func_dic[choice]()
    elif choice == '8':
        break
    else:
        print("你输入的方法不存在")
posted @ 2019-08-14 21:18  黑井白子  阅读(387)  评论(0编辑  收藏  举报
Live2D