Python-购物车系统

# coding=utf-8
import os, pickle


class color:
    def echo_error(self, red):
        print(f"\033[31;1m {red}\033[0m".strip())

    def echo_ok(self, green):
        print(f"\033[32;1m {green}\033[0m".strip())

    def echo_warn(self, warning):
        print(f"\033[33;1m {warning}\033[0m".strip())


color = color()


def file_open(file, mode, *args):
    if mode == "wb":
        data = args[0]
        with open(file, mode) as f:
            pickle.dump(data, f)
    elif mode == "rb":
        with open(file, mode) as f:
            user_dict = pickle.load(f)
            return user_dict
    elif mode == "clear":
        with open(file, mode) as f:
            data = args[0]
            pickle.dump(data, f)


def user(user, pwd, mode):
    file = user + ".db"
    if mode == "regist":
        if not os.path.isfile(file):
            user_dict = {"name": user, "pwd": pwd, "stat": 0}
            file_open(file, "wb", user_dict)
            color.echo_ok("注册成功!")
        else:
            color.echo_error("用户已注册")

    elif mode == "login":
        if os.path.isfile(file):
            user_dict = file_open(file, "rb")
            if user_dict["name"] == user and user_dict["pwd"] == pwd:
                color.echo_ok("登录成功")
                return user_dict
            else:
                color.echo_error("登录失败,用户名或密码错误")
        else:
            color.echo_error("不存在此用户,请先注册")
            return None
    else:
        color.echo_error("错误")


def shopping(user_dict, list_goods):
    if user_dict["shopping_car"]:
        list_shopping = user_dict["shopping_car"]
    else:
        list_shopping = []

    while True:
        color.echo_ok("商品列表如下:\n"
                      "##########################\n"
                      "序号 商品名称 商品价格")
        for i, k in enumerate(list_goods):
            print(i, k["name"], k["price"])
        chooice = input("请输入购买商品序号 [t 查看购物车 q 退出]")
        if not chooice: continue

        if chooice.isdigit() and 0 <= int(chooice) < len(list_goods):
            num = input("请输入要购买的数量")
            if num.isdigit():
                num = int(num)
            else:
                color.echo_error("数量必须是正整数")
            goods = {"name": list_goods[int(chooice)]["name"], "num": num,
                     "total_price": list_goods[int(chooice)]["price"] * num}

            list_shopping.append(goods)
            color.echo_ok("购物成功!")
        elif chooice == "t":
            color.echo_ok("#########购物清单##########")
            print("商品名   数量    价格")
            if len(list_shopping) == 0:
                color.echo_warn("您没有购买任何东西..")
                any = input("输入任意字符继续..")
                if any: continue
                continue
            price = 0
            for i in list_shopping:
                print(i["name"], i["num"], i["total_price"])
                price += i["total_price"]
            chooice = input("总价格:%s,是否购买(yes/no),[e 查看余额 c 清空购物车]:" % price)
            if chooice == "c":
                list_shopping = []
                user_dict["shopping_car"] = list_shopping
                color.echo_ok("购物车清空成功")
                file_open(user_dict["name"] + ".db", "wb", user_dict, "clear")
            elif chooice == "e":
                color.echo_ok("您的余额为 %s" % user_dict["money"])
            elif chooice == "yes":
                if user_dict["money"] > price:
                    res_money = user_dict["money"] - price
                    color.echo_ok(f"购买成功,您的余额为 {res_money}")
                    list_shopping = []
                    user_dict["shopping_car"] = list_shopping
                    user_dict["money"] = res_money
                    file_open(user_dict["name"] + ".db", "wb", user_dict, "clear")
                    any = input("输入任意字符继续..")
                    if any: continue
                else:
                    color.echo_error("您的余额不够买这些东西,挣点钱再来吧。")
            elif chooice == "no":
                color.echo_warn("您取消购买")
                any = input("输入任意字符继续..")
                if any: continue

        elif chooice == "q":
            color.echo_warn("退出程序")
            break


def start(list_goods):
    while True:
        print('''
        1. 注册
        2. 登录并购物
        3. 登出
        ''')
        chooce = input(">>>").strip()
        if chooce == "1":
            username = input("请输入你的用户名:").strip()
            pwd = input("请输入你的密码:").strip()
            user(username, pwd, "regist")
        elif chooce == "2":
            username = input("请输入你的用户名:").strip()
            pwd = input("请输入你的密码:").strip()
            user_dict = user(username, pwd, "login")
            if user_dict == None: continue
            if user_dict["stat"] == 0:
                money = int(input("请输入你的首冲金额:"))
                user_dict["stat"] += 1
                user_dict["money"] = money
                user_dict["shopping_car"] = []
                color.echo_ok("恭喜,充值成功!,可以尽情购物了~")
                file_open(user_dict["name"] + ".db", "wb", user_dict)
                shopping(user_dict, list_goods)
            else:
                shopping(user_dict, list_goods)

        elif chooce == "3":
            break
        else:
            color.echo_error("非法操作,请重输入")


if __name__ == "__main__":
    list_goods = [
        {"name": "苹果", "price": 10},
        {"name": "芒果", "price": 20},
        {"name": "提子", "price": 30},
        {"name": "香蕉", "price": 40},
    ]

start(list_goods)

转载于:https://www.cnblogs.com/qinyujie/p/11502249.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个简单的 Python 购物车系统,可以实现用户注册、登录、浏览商品、添加购物车、结算等基本功能。 ```python # 定义商品数据 items = { "1": {"name": "iPhone 12", "price": 7499}, "2": {"name": "AirPods Pro", "price": 1999}, "3": {"name": "iPad Pro", "price": 7999}, "4": {"name": "MacBook Pro", "price": 12999}, "5": {"name": "Apple Watch", "price": 3299} } # 定义用户数据 users = {} # 登录函数 def login(): username = input("请输入用户名:") password = input("请输入密码:") if username in users and users[username]["password"] == password: print("欢迎回来,{}!".format(username)) return username else: print("用户名或密码错误,请重新登录!") return None # 注册函数 def register(): username = input("请输入用户名:") if username in users: print("用户名已存在,请重新注册!") return False else: password = input("请输入密码:") users[username] = {"password": password, "shopping_cart": {}} print("注册成功,请登录!") return True # 浏览商品函数 def browse_items(): print("以下是我们的商品列表:") for num, item in items.items(): print("{0}. {1} - {2} 元".format(num, item["name"], item["price"])) # 添加购物车函数 def add_to_cart(username): num = input("请输入要购买的商品编号,按回车结束:") if num not in items: print("商品编号不存在,请重新选择!") return else: item = items[num] if num in users[username]["shopping_cart"]: users[username]["shopping_cart"][num]["quantity"] += 1 else: users[username]["shopping_cart"][num] = {"name": item["name"], "price": item["price"], "quantity": 1} print("{0} 已添加到购物车!".format(item["name"])) # 查看购物车函数 def view_cart(username): cart = users[username]["shopping_cart"] if not cart: print("您的购物车为空,快去添加一些商品吧!") else: print("您的购物车清单如下:") total_price = 0 for num, item in cart.items(): print("- {0} * {1}:{2} 元".format(item["name"], item["quantity"], item["price"] * item["quantity"])) total_price += item["price"] * item["quantity"] print("总价:{0} 元".format(total_price)) # 结算函数 def checkout(username): cart = users[username]["shopping_cart"] if not cart: print("您的购物车为空,不能结算!") else: total_price = 0 for num, item in cart.items(): total_price += item["price"] * item["quantity"] print("您的订单总价为 {0} 元,确认要结算吗?".format(total_price)) confirm = input("请输入 y 或 n:") if confirm == "y": print("结算成功,感谢您的购买!") users[username]["shopping_cart"] = {} else: print("取消结算,欢迎继续购物!") # 主程序 print("欢迎来到 Apple Store!") while True: print("=" * 30) print("请选择您的操作:") print("1. 登录") print("2. 注册") print("3. 浏览商品") print("4. 添加购物车") print("5. 查看购物车") print("6. 结算") print("7. 退出") choice = input("请输入操作编号:") if choice == "1": username = login() elif choice == "2": register() elif choice == "3": browse_items() elif choice == "4": if "username" not in locals(): print("请先登录!") else: add_to_cart(username) elif choice == "5": if "username" not in locals(): print("请先登录!") else: view_cart(username) elif choice == "6": if "username" not in locals(): print("请先登录!") else: checkout(username) elif choice == "7": print("欢迎下次光临!") break else: print("输入有误,请重新选择!") ``` 程序功能说明: 1. 定义了商品数据和用户数据,以及登录、注册、浏览商品、添加购物车、查看购物车、结算等函数; 2. 主程序循环等待用户输入操作编号,根据不同的操作调用相应的函数; 3. 用户登录后,其购物车数据将保存在 `users` 字典中。 希望这个示例对您有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值