这几天, 一直在学 python, 跟着视频老师做了一个比较简单的 python 购物车, 感觉不错, 分享一下
- products = [['Iphone8',6888],['MacPro',14800],['小米 6',2499],['Coffee',31],['Book',80],['Nike Shoes',799]]
- shopping_cart = []
- #run_flag = True #标志位
- exit_flag = False
- while not exit_flag:
- print("--------- 商品列表 ------------")
- for index,p in enumerate(products):
- print("%s, %s %s" %(index,p[0],p[1] ))
- choice = input("请输入你要买的商品编号:")
- if choice.isdigit(): #判断是不是 str 类型
- choice = int(choice)
- if choice>= 0 and choice <len(products):
- shopping_cart.append(products[choice])
- print("Add product %s into shopping_cart." %(products[choice]))
- else:
- print("该商品的编号不存在")
- elif choice == 'q':
- if len(shopping_cart)>0:
- print("------- 你已经购买以下商品 --------")
- for index,p in enumerate(shopping_cart) :
- print("%s, %s %s" % (index, p[0], p[1]))
- #break
- #run_flag = False
- exit_flag = True
第二个是我在上网找来的, 不过改优化了一点点
- #!/usr/bin/env.python
- # -*- coding: utf-8 -*-
- """
- -------------------------------------------------
- File Name: shopping
- Description :
- Author : lwh
- date: 2019/2/28
- -------------------------------------------------
- -------------------------------------------------
- """
- #定义一个商品的列表
- product_list = [
- ('iphone',5000),
- ('coffee',31),
- ('bicyle',888),
- ('iwatch,2666'),
- ('Mac Pro',15000),
- ('book',88)]
- shopping_list = [] #空列表, 存放购买的商
- money = input("请输入你的工资:")
- if money.isdigit(): # isdigit() 用来检 #检测字符串是否只由数字组成, 是则返回 True, 否则 False
- money = int(money)
- while True:
- for index,i in enumerate(product_list): #index 作为下标索引
- # enumerate() 函数用于将一个可遍历的数据对象 (如列表, 元组或字符串) 组合为一个索引序列, 同时列出数据和数据下标, 一般用在 for 循环当中.
- print(index,i[0],i[1]) #qi'qin
- user_choice = input("请输入你要购买的商品:")
- if user_choice.isdigit() : #判断
- user_choice = int(user_choice)
- if user_choice <len(product_list) and user_choice>= 0:
- product_choice = product_list[user_choice]
- if product_choice[1] < money: #买得起
- shopping_list.append(product_choice) # 买得起, 就放入购物车
- money -= product_choice[1]
- print("添加 %s 到你的购物车了, 你的余额为 : \033[31;1m%s\033[0m" % (product_choice, money))
- else:
- print("\033[41;1m 你的余额只剩 %s 啦, 不够买该商品, 请重新选择!\033[0m" % money)
- print("----------- 购 物 车 ------------")
- for s_index, s in enumerate(shopping_list):
- print(s_index,s)
- print("----------- 商 品 ------------")
- print("你的余额为:\033[31;1m%s\033[0m" % money)
- else:
- print("没有这个商品")
- elif user_choice == "q" :
- print("------- 购 物 清 单 ---------")
- for s_index,s in enumerate(shopping_list):
- print(s_index,s)
- print("----------- 购 物 清 单 ------------")
- print("你的余额为 : \033[31;lm%s\033[0m" % money)
- exit()
- else:
- print("输入错误, 没有这个商品, 请重新输入:")
- else:
- print("输入错误, 请重新输入:")
第二个购物车原码网站: https://www.cnblogs.com/cxylff/p/8468500.html
来源: http://www.bubuko.com/infodetail-2971628.html