Python项目实战

第一章:猜谜游戏

第二章:街霸游戏

第三章:购物系统

第四章:搜索引擎

首页 > Python项目实战 > 第三章:购物系统 > 3.1节: 简单商城购物系统

3.1节: 简单商城购物系统

薯条老师 2021-03-03 16:25:10 237629 0

编辑 收藏

商城购物系统

本节实现一个字符界面的简单商城购物系统。项目需求如下:

① 列出所有商品

输出举例:

您好,欢迎使用薯条橙子在线购物系统,以下是商城中的所有商品

+----+--------+-----------+

| id | 商品名 |  售价     |

+----+--------+-----------+

|  1 | 洗发水 |   22      |

|  2 | 牙膏   |   15      |

|  3 | 宠物绳 |   29      |

|  4 | 面包   |   16      |

|  5 | 啤酒   |   8       |

|  6 | 咖啡   |   30      |

+----+--------+-----------+

② 对商品按售价进行排序

您好,输入指令asc对商品按售价进行升序排序,输入指令desc对商品按售价进行降序排序。

输出举例:

asc:

+----+--------+-----------+

| id | 商品名 |  售价     |

+----+--------+-----------+

|  8 | 啤酒   |   8       |

|  2 | 牙膏   |   15      |

+----+--------+-----------+

 加入购物车

请输入商品编号:__

您好,已将商品xxx加入购物车。

④ 查看购物车

输出举例:

这是您的购物清单:

+----+--------+-----------+

| id | 商品名 |  售价     |

+----+--------+-----------+

|  8 | 啤酒   |   8       |

|  2 | 牙膏   |   15      |

+----+--------+-----------+

  删除购物车指定商品

请输入需要移除的商品编号:__

您好,已将商品从购物车中移除。

 

⑥ 下单结账

这是您的购物清单:

+----+--------+-----------+

| id | 商品名 |  售价     |

+----+--------+-----------+

|  1 | 洗发水 |   22      |

|  5 | 啤酒   |   8       |

|  6 | 咖啡   |   30      |

+----+--------+-----------+

总价:60元,输入指令0进行付款,输入指令1继续购物。

完整源码

本节的购物系统采用面向过程的方法进行实现,在下节的项目实战中,会实现一个面向对象版本的购物系统。理解下面的代码,需要同学们掌握回调函数的基础知识:

# __author__ = 薯条老师
# __desc__ = 简单的在线商城购物系统chipscoco



def convert_dict_2_list(data):
    """
    :param data: a dict of  goods,  e.g:{
            1: {"name": "洗发水", "price": 22},
            2: {"name": "牙膏", "price": 15},
        },
    :return: a list of goods , e.g:[{"id": 1, "name": "洗发水", "price": 22}]
    """
    goods = []
    for _ in data:
        goods.append({"id": _, "name": data[_]["name"], "price": data[_]["price"]})
    return goods
    
    
    
def show(goods, flag = 0):
    """
    :param goods: goods table, e.g:{
            1: {"name": "洗发水", "price": 22},
            2: {"name": "牙膏", "price": 15},
        }, or [{"id": 1, "name": "洗发水", "price": 22}, ]
    :return:
    """
    tr = "+"+"-"*5+"+"+"-"*16+"+"+"-"*10+"+"
    heading = "|{:^5s}|{:^13s}|{:^8s}|".format("id", "商品名", "售价")
    print(tr+"\n"+heading+"\n"+tr)
    if flag == 0:
        for id_ in goods:
            print("|{0:^5s}|{1:{3}^8s}|{2:^10s}|".format(str(id_), goods[id_]["name"],
                                                     str(goods[id_]["price"]), chr(12288)))
    else:
        for item in goods:
            print("|{0:^5s}|{1:{3}^8s}|{2:^10s}|".format(str(item["id"]), item["name"],
                                                         str(item["price"]), chr(12288)))
    print(tr)
    
    
    
def sort_goods(chipscoco):
    """
       :param chipscoco: a dict object indicates online shopping system chipscoco,
       e.g:{
        "goods":{
            1: {"name": "洗发水", "price": 22},
            2: {"name": "牙膏", "price": 15},
        },
        "shopping_cart":{"洗发水": 22, }
       }
       :return:
    """
    
    goods = convert_dict_2_list(chipscoco["goods"])
    data_size = len(goods)
    command = input("您好,输入指令<asc>对商品按售价进行升序排序,"
                    "输入指令<desc>对商品按售价进行降序排序:____\b\b\b\b").lower()
    if command == "asc":
        for index_outer in range(data_size-1):
            for index_inner in range(data_size-1-index_outer):
                if goods[index_inner]["price"] > goods[index_inner+1]["price"]:
                    goods[index_inner], goods[index_inner+1] =\
                        goods[index_inner+1], goods[index_inner]
        show(goods, flag=1)
    elif command == "desc":
        # 读者可以自行实现一个降序排序的功能
        pass
    else:
        print("您输入的指令有误!")
        
        
        
def add_goods(chipscoco):
    """
       :param chipscoco: a dict object indicates online shopping system chipscoco,
       e.g:{
        "goods":{
            1: {"name": "洗发水", "price": 22},
            2: {"name": "牙膏", "price": 15},
        },
        "shopping_cart":{
            1: {"name": "洗发水", "price": 22},
            2: {"name": "牙膏", "price": 15},
        }
       :return:
    """
    
    id_ = int(input("请输入商品id:__\b\b"))
    if id_ in chipscoco["goods"] and id_ not in chipscoco["shopping_cart"]:
        chipscoco["shopping_cart"][id_] = {"name": chipscoco["goods"][id_]["name"],
                                           "price":  chipscoco["goods"][id_]["price"]}
        print("您好,已将商品{}加入购物车".format(chipscoco["goods"][id_]["name"]))
    else:
        print("您输入的商品编号有误!")
        
        
        
def show_shopping_cart(chipscoco):
    """
       :param chipscoco: a dict object indicates online shopping system chipscoco,
       e.g:{
        "goods":{
            1: {"name": "洗发水", "price": 22},
            2: {"name": "牙膏", "price": 15},
        },
        "shopping_cart":{
            1: {"name": "洗发水", "price": 22},
            2: {"name": "牙膏", "price": 15},
        }
       :return:
    """
    
    print("这是您的购物清单:")
    show(chipscoco["shopping_cart"])
    
    
    
def show_all_goods(chipscoco):
    """
       :param chipscoco: a dict object indicates online shopping system chipscoco,
       e.g:{
        "goods":{
            1: {"name": "洗发水", "price": 22},
            2: {"name": "牙膏", "price": 15},
        },
        "shopping_cart":{"洗发水": 22}
       }
       :return:
    """
    
    print("以下是商城中的所有商品:")
    show(chipscoco["goods"])
    
    
    
def shopping():
    chipscoco = {
        "goods": {
            1: {"name": "洗发水", "price": 22},
            2: {"name": "牙膏", "price": 15},
            3: {"name": "宠物绳", "price": 29},
            4: {"name": "面包", "price": 16},
            5: {"name": "啤酒", "price": 8},
            6: {"name": "咖啡", "price": 30},
        },
        "shopping_cart": {}
    }
    prompt = "您好,欢迎使用薯条橙子在线购物系统chipscoco,输入<>中对应的指令来使用购物系统:\n" \
             "<1>:查看所有商品\n<2>:对商品按售价进行排序(asc表示升序,desc表示降序)\n" \
             "<3>:添加商品到购物车\n<4>:查看购物车\n<5>:删除购物车指定商品\n<6>:下单结账\n"
    """
     (1) 定义一个字典对象,键名表示数字指令,键值为指令所对应的回调函数
     (2) 回调函数需遵循统一的接口规范,本节程序实战中的回调函数都带有一个chipscoco参数,该参数表示购物系统chipscoco的商品及购物车数据
     """
    orders = {1: show_all_goods, 2: sort_goods, 3: add_goods, 4: show_shopping_cart}
    while True:
        print(prompt)
        try:
            order = int(input("请输入<>中的指令:_\b"))
        except:
            print("请输入数字指令来使用该购物系统")
            continue
        print("您输入了非法的指令") if order not in orders else orders[order](chipscoco)
        if input("按下键盘任意键继续购物或者输入quit退出购物系统:____\b\b\b\b").lower() == "quit":
            break
            
            
            
if __name__ == "__main__":
    shopping()

以上程序只实现了查看所有商品,添加商品,对商品按售价进行排序等功能,读者需要在以上代码基础上继续实现删除购物车,下单结账等功能。

程序的输出界面

shopping.jpg

最具实力的小班培训

来这里参加Python和Java小班培训的学员大部分都找到了很好的工作,平均月薪有11K,学得好的同学,拿到的会更高。由于是小班教学,所以薯条老师有精力把每位学员都教好。打算参加线下小班培训的同学,必须遵守薯条老师的学习安排,认真做作业和项目。把知识学好,学扎实,那么找到一份高薪的工作就是很简单的一件事。

(1) Python后端工程师高薪就业班,月薪11K-18K,免费领取课程大纲
(2) Python爬虫工程师高薪就业班,年薪十五万,免费领取课程大纲
(3) Java后端开发工程师高薪就业班,月薪11K-20K, 免费领取课程大纲
(4) Python大数据分析,量化投资就业班,月薪12K-25K,免费领取课程大纲

扫码免费领取学习资料:



欢迎 发表评论: