python - 函数购物车(含文件读取)

作业需求:

1,启动程序,用户可选择四个选项:登录,注册,购物,退出。
2,用户注册,用户名不能重复,注册成功之后,用户名密码记录到文件中。
3,用户登录,用户名密码从文件中读取,进行三次验证,验证不成功则退出整个程序。
4,用户登录成功之后才能选择购物功能进行购物,购物功能(就是将购物车封装到购物的函数中)。
5,退出则是退出整个程序。

#auth_Mouni
#date 2019-01-18
def man():
    while 1:
        choise = input("[1]登录 [2]注册 [3]购物 [4]退出 请选择:>>")
        if choise == "1":
            login()
        elif choise == "2":
            register()
        elif choise == "3":
            print("请先登录,再进行购物".center(15,"*"))
            login()
        elif choise == "4":
            print("已退出系统".center(15,"*"))
            break
        else:
            print("输入有误重新输入")

def register():
    freg = open('pd_file', 'a+', encoding='utf-8')
    freg.seek(0)
    users_info = {}  # 定义存放用户名,密码的 字典
    for line in freg.readlines():        # 逐行读取用户名,密码,并存储到字典中
        users = line.strip().split(',')
        users_info[users[0]] = users[1]

    while True:
        username = input('请注册用户名:>>').strip()
        if username in users_info.keys():
            print('用户名已存在,请重新注册')
            man()
        else:
            password = input('请输入密码:').strip()  # 确认两次密码输入
            cpasswd = input('请确认密码:').strip()
            if username and password and cpasswd:
                if password != cpasswd:
                    print('两次输入密码不一致,请重新注册!')
                    register()
                else:
                    freg.write(username + ',' + password + '\n') # 写入密码文件
                    print('注册成功')
                    break
    freg.close()

# def login():
#     with open('pd_file_1', 'r', encoding='utf-8') as f:
#         users_info = {}
#         username = input('请输入用户名:>>')
#         for line in f.readlines():
#             users = line.strip().split(',')
#             users_info = {"name": users[0], "pws": users[1]}  # 循环获取 帐号和密码
#             # print("用户名:%s  密码%s" % (users_info['name'], users_info['pws']))  # 用户名 密码
#             # print(users_info["pws"])   # 密码
#             if username == users_info["name"]:  # 判断用户是否存在
#                 while 1:
#                     password = input('请输入密码:')
#                     if password == users_info["pws"]:  # 判断用户密码是否正确
#                         print("登录系统成功".center(15,"*"))
#                         shoping()
#                     else:
#                         n = 3
#                         while n > 0:  # 三次错误密码循环
#                             n -= 1
#                             password = input('用户或密码错误,请重新输入,还有%s机会:>>' % n)
#                             if n == 1:
#                                 print("用户或密码错误,注册或重新登录")
#                                 man()
#                     break
#         else:
#             flog = "不存在" # 标记用
#         if flog == "不存在":
#             print("用户不存在,请注册")
#             man()
def login():
    with open('pd_file', 'r', encoding='utf-8') as f:
        users_info = {}
        username = input('请输入用户名:>>')
        for line in f.readlines():
            users = line.strip().split(',')
            users_info = {"name": users[0], "pws": users[1]}  # 循环获取 帐号和密码
            # print("用户名:%s  密码%s" % (users_info['name'], users_info['pws']))  # 用户名 密码
            # print(users_info["pws"])   # 密码
            if username == users_info["name"]:  # 判断用户是否存在
                while 1:
                    password = input('请输入密码:>>')
                    if password == users_info["pws"]:  # 判断用户密码是否正确
                        print("登录系统成功".center(15,"*"))
                        shoping()
                    else:
                        n = 3
                        while n > 0:  # 三次错误密码循环
                            n -= 1
                            print('用户或密码错误,请重新输入,还有%s机会' % n)
                            password = input('请输入密码:>>')
                            if password == users_info["pws"]:  # 判断用户密码是否正确
                                print("登录系统成功".center(15, "*"))
                                shoping()
                            if n == 1:
                                print("用户或密码错误,注册或重新登录")
                                man()
                    break
        else:
            flog = "不存在" # 标记用
        if flog == "不存在":
            print("用户不存在,请注册")
            man()

def shoping():
    product_lst = [
        {"name": " 电脑 ", "price": 1999,"ID":0},
        {"name": " 鼠标 ", "price": 10,"ID":1},
        {"name": " 游艇 ", "price": 20,"ID":2},
        {"name": " 美女 ", "price": 998,"ID":3}]
    shop_car = []
    cost_money = 0
    ID_lst = []
    print("欢迎光临幸福超市".center(15,"*"))
    while 1:
        salary = input("输入金额进行购物:>>")
        if salary.isdigit():
            salary = int(salary)
            break
        else:
            print("输入金额有误,请重新输入")

    chajia = 0
    while 1:
        print("买商品信息如下".center(20, "*"), "\nID", "商品名称".center(9, " "), "价格")
        for i in range(len(product_lst)):
            print(i, product_lst[i]["name"].center(11, " "), product_lst[i]["price"])  # 输出商品列表信息
            # print(i + 1, product_lst[i]["name"].center(11, " "), product_lst[i]["price"])  # 输出商品列表信息

        choise = input("输入ID将商品加入购物车,[N]结算 [Q]退出:>>")
        if choise.isdigit():  # 开始购物
            index = int(choise)  # 购物车的 ID 下标
            if int(index) < 0 or int(index) >= len(product_lst):
                print("选择有误,重新选择:>>")
                continue
            else:
                for item in shop_car:
                    if item["ID"] == index:
                        item["totle"] += 1
                        ID_lst.append(product_lst[index]["ID"])
                        break
                else:  # 第一次商品加入购物车 增加ID项  和 数量项
                    shop_car.append({"ID": index, 'name': product_lst[index]['name'], "price": product_lst[index]['price'],"totle": 1})
                    ID_lst.append(product_lst[index]["ID"])
        elif choise.upper() == "Q":  # 退出时 不计算商品
            print("退出购物商城,无购物".center(15, "*"))
            man()
        elif choise == "n":  # 结算 商品
            while 1:
                for i in range(len(shop_car)):  # 打印购物车内商品信息
                    cost_money += shop_car[i]["price"] * shop_car[i]["totle"]
                while 1:  # 进入移除商品循环
                    if len(shop_car) == 0:
                        print("购物车内无商品")
                        print("购物车已清空","\n无消费,余%s元" % (int(salary) - int(cost_money)))
                        man()
                    if int(salary) > int(cost_money):  # 购物金额充足时
                        print("您购买商品信息如下".center(20, "*"), "\n商品名称", "数量".center(10, " "), "价格")
                        for i in range(len(shop_car)):
                            print(shop_car[i]["name"], str(shop_car[i]["totle"]).center(12, " "), shop_car[i]["price"])
                        print("共消费%s元,余%s元" % (int(cost_money), int(salary) - int(cost_money)))
                        exit()
                    else:  # 购物金额不足时
                        chajia = int(salary) - int(cost_money)  # 差的钱数

                        print("购物金额不足,请移除部分商品,还差%s元" % (chajia))
                        print("ID", "商品名称".center(5, " "), "数量".center(7, " "), "价格")
                        for i in range(len(shop_car)):  # 打印购物车内要移除的商品列表
                            print(shop_car[i]["ID"], shop_car[i]["name"].center(7, " "),
                                  str(shop_car[i]["totle"]).center(9, " "), shop_car[i]["price"])  # 输出商品列表信息
                        while 1:
                            choise = input("输入移除商品ID,退出商城请按[Q]:>>")  # 选择移除商品 ID
                            if choise.isdigit():
                                choise = int(choise)
                                if choise >= 0 and choise in ID_lst:  # 存在一个小BUG
                                    break
                                else:
                                    print("输入ID有误,请重新输入")
                                    continue
                            elif choise.upper() == "Q":
                                man()
                            else:
                                print("输入ID有误,请重新输入")
                        for item in shop_car:
                            if item["ID"] == choise and item["totle"] == 1:
                                cost_money -= item["price"]  # 商品为1件时移除 花费钱还回来
                                shop_car.remove(item)
                                ID_lst.remove(int(item["ID"]))

                            elif item["ID"] == choise:  # 商品数量 减少
                                cost_money -= item["price"]
                                item["totle"] -= 1
                                ID_lst.remove(int(item["ID"]))

            exit()
        else:
            print("输入有误,请重新输入:>>")

def quit():
    print("已退出系统".center(15, "*"))
    exit()

man()```

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值