脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python实现购物车小程序

python实现购物车小程序

2022-09-14 13:55%木糖醇---LHY% Python

这篇文章主要为大家详细介绍了python实现购物车小程序,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了python实现购物车小程序的具体代码,供大家参考,具体内容如下

功能实现:

(1)可以查看购物车的商品,和余额

(2)可以显示商品列表,根据商品的编号选择商品

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#定义一个列表存放商品信息
products=[('iphone',5800),('bike',220),('vivo',2000),('book',20)]
shopping_list=[]#将购买的商品存在列表shopping_list 中
salary=input("输入你的工资")
#判断输入的工资是否是数字
if salary.isdigit():
    salary=int(salary)#把输入的工资转换为整型
    while True:
        # for i in products:输出商品编号和商品信息两种方式均可
        #     print(products.index(i),i)
        for index,i in enumerate(products):
            print(index,i)
        user_choice=input("选择要买的商品")
        #通过输入商品编号来选择商品
        if user_choice.isdigit():
            user_choice=int(user_choice)
            if user_choice>=0 and user_choice<len(products):
                p_item=products[user_choice]
                if p_item[1]<=salary:
                    shopping_list.append(p_item)#把买的东西放到购物车
                    salary-=p_item[1]#计算买完东西以后剩下的钱
                    print("add %s into shopping car,you current salary %s" %(p_item[0],salary))
                else:
                    print("\033[41;1m你的余额只剩[%s]了,不能买了,按q退出\033[0m" %salary)
            else:
                print("商品不存在")
        elif user_choice=='q':
            print("购物车的商品如下所示")
            for p in shopping_list:
                print(p)
            print("余额",salary)
            break
        else:
            print("invalid input")
else:
    print("invalid input")

效果:

python实现购物车小程序

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://www.cnblogs.com/come-on-baby/p/9480552.html

延伸 · 阅读

精彩推荐