Explain how to implement a shopping cart in Python based on file operations

coldplay.xixi
Release: 2021-03-01 09:59:32
forward
2360 people have browsed it

Explain how to implement a shopping cart in Python based on file operations

免费学习推荐:python视频教程

Python 基于文件操作实现购物车

学习Python有一段时间了,想着需要找些东西写一下来巩固下基础,看到了购物车然后想着能不能利用已经学过的实现以下功能。但是比较简单的实现也没啥意义,只用几个循环和判断写出来也没用到些啥于是想着能不能更进一步修改一下,做一个优化。刚好学到的文件操作可以存储一些信息。于是,优化的想法就有了,废话不多说,上代码。

# coding:utf-8# author:w_uimport time# 获取当前时间函数,用于显示交易时间以及当前时间def get_time():
    now_time = time.strftime("%y-%m-%d %H:%M:%S")
    return now_time# 定义好各个文件操作需要用到的中间媒介user_information = {}  user_salary = {}       admin_information = {}shopping_list = []add_product = []shopping_car = []print("*" * 25 + "欢迎光临".center(0) + "*" * 25)while True:
    print("现在的时间是:\033[32;1m%s\033[0m" % get_time())
    print("您是用户或者是商家:\n 1.用户\n 2.商家")
    while True:
        user_choose1 = input(">>>:")
        # 由于用户输入并不可靠,所以这里判断一下用户输入信息!以下皆是如此
        if user_choose1.isdigit():
            user_choose1 = int(user_choose1)
            if user_choose1 == 1:
                while True:
                    print("请选择注册、登录或者退出:\n 1.注册 \n 2.登录 \n 3.退出")
                    user_choose2 = input(">>>")
                    if user_choose2.isdigit():
                        user_choose2 = int(user_choose2)
                        if user_choose2 == 1:
                            username = input("请输入用户名:")
                            password = input("请输入密码:")
                            user_information[username] = password                            # 将用户注册信息存放到字典并以字符串形式存放到文件里,因为写模式会把原信息覆盖所以这里选择使用追加方式打开文件
                            with open("user_information", 'a+', encoding="utf-8") as f:
                                f.write(str(user_information))
                            # 判断输入工资是否是纯数字,因为工资不可能是字母
                            while True:
                                salary = input("请输入工资:")
                                if salary.isdigit():
                                    salary = int(salary)
                                    user_salary[username] = salary                                    # 将用户输入的工资绑定到对印度个用户名上,用于登录查看用户工资
                                    with open("user_salary", 'a+', encoding="utf-8") as f:
                                        f.write(str(user_salary))
                                    break
                                else:
                                    print("非法字符!请重新输入!")
                        elif user_choose2 == 2:
                            username_input = input("请输入用户名:")
                            password_input = input("请输入密码:")
                            with open("user_information", 'r+', encoding="utf-8") as f:
                                data = f.read()
                                # 使用eval函数将文件读取的字符串形式转换为为字典
                                user_information = eval(data)
                            if user_information[username_input] == password_input:
                                print("登陆成功!")
                                print("*" * 25 + "欢迎光临本店".center(0) + "*" * 25)
                                # 获取用户工资
                                with open("user_salary", 'r+', encoding="utf-8") as f:
                                    data1 = f.read()
                                    user_salary = eval(data1)
                                print(f"你现在的工资为\033[32;1m{user_salary[username_input]}\033[0m")
                                # 获取购物车的信息并打印
                                with open("shopping_list", 'r+', encoding="utf-8") as f:
                                    data2 = f.read()
                                    shopping_list = eval(data2)
                                while True:
                                    for item in enumerate(shopping_list):
                                        print(item)
                                    user_choose3 = input("老板买点啥:")
                                    if user_choose3.isdigit():
                                        user_choose3 = int(user_choose3)
                                        for i in range(0, len(shopping_list) + 1):
                                            if user_choose3 == i:
                                                shopping_car.append(shopping_list[user_choose3][0])
                                                shopping_time = get_time()
                                                print("购买\033[32;1m %s\033[0m* 1" % shopping_list[user_choose3][0])
                                                print("交易时间:\033[32;1m %s\033[0m* 1" % shopping_time)
                                                # 将用户购买的物品存入到购物车文件里,并且记录交易时间
                                                with open("shopping_car", 'a+', encoding="utf-8") as f:
                                                    f.write(str(shopping_car))
                                                    f.write(str(shopping_time))
                                                # 购买商品的花费,需要更新购买后用户的工资
                                                if user_salary[username_input] >= int(shopping_list[user_choose3][1]):
                                                    user_salary[username_input] = user_salary[username_input] - int(
                                                        shopping_list[user_choose3][1])
                                                print(f"剩余工资:\033[33;1m{user_salary[username_input]}\033[0m")
                                                # 购买后用户所剩下的工资重新写入到文件里
                                                with open("user_salary", 'r+', encoding="utf-8") as f:
                                                    f.write(str(user_salary))
                                                while True:
                                                    user_choose4 = input("您需要继续购买吗?\n 1.继续购物\n 2.退出\n")
                                                    if user_choose4.isdigit():
                                                        user_choose4 = int(user_choose4)
                                                        if user_choose4 == 1:
                                                            break
                                                        else:
                                                            print("*" * 25 + "购物车".center(0) + "*" * 25)
                                                            print(shopping_car)
                                                            print(
                                                                f"剩余工资:\033[33;1m{user_salary[username_input]}\033[0m")
                                                            exit()
                            else:
                                print("该用户不存在!")
                        elif user_choose2 == 3:
                            exit()
                        else:
                            print("输入错误,请重新输入!")
            elif user_choose1 == 2:
                # 这里设置商家是一个管理员的模式,所以商家不用注册直接登陆查看
                print("请先登录:")
                admin_input = input("请输入用户名:")
                admin_password_input = input("请输入密码:")
                with open("admin_information", 'r+', encoding="utf-8") as f:
                    data = f.read()
                    admin_information = eval(data)
                # 校验信息
                if admin_information[admin_input] == admin_password_input:
                    print("*" * 25 + "欢迎进入管理系统".center(0) + "*" * 25)
                    print("以下是现货架上商品有")
                    with open("shopping_list", 'r+', encoding="utf-8") as f:
                        data2 = f.read()
                        shopping_list = eval(data2)
                    for item in enumerate(shopping_list):
                        print(item)
                    while True:
                        admin_choose = input("是否需要添加商品:\n 1.添加商品 \n 2. 退出 \n >>>:")
                        if admin_choose.isdigit():
                            admin_choose = int(admin_choose)
                            if admin_choose == 1:
                                add_product_name = input("请输入商品名:")
                                add_product_price = input("请输入价格:")
                                add_product.append(add_product_name)
                                add_product.append(add_product_price)
                                shopping_list.append(add_product)
                                with open("shopping_list", 'r+', encoding="utf-8") as f:
                                    f.write(str(shopping_list))
                            elif admin_choose == 2:
                                print("感谢使用!")
                                exit()
                            else:
                                print("输入错误")
                        else:
                            print("输入错误!")
Copy after login

写到这,实现基本的功能还是没有问题的,可以将用户信息、商家信息等等等等存入文件里,下次再需要使用的时候直接从文件里调用出来,就不用像平常的运行一遍输入一遍啦,用户的工资也是可以保存的,商家可以像货架上添加商品。商家是作为管理员的角色,所以初始的账号密码是固定存在一个文件里。本来想添加一个修改商家信息,但是想想还是一样的操作,就直接省了这一步。

大量免费学习推荐,敬请访问python教程(视频)

The above is the detailed content of Explain how to implement a shopping cart in Python based on file operations. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!