Python-列表做的购物车小程序

一、流程为,输入你有多少钱,然后循环购买商品,输入‘q’ 退出程序

 1 goods=[['苹果',6500],['华为',4999],['小米',2999],['oppo',3599]]  #初始化列表,填入数据
 2 mgoods=[]
 3 exit_flag = False              #设置一个开关
 4 money=input("输入你的钱:")
 5 if money.isdigit():          #判断是否为数字
 6     while not exit_flag:
 7         for index, item in enumerate(goods):   #循环遍历列表内容,enumerate方法是把列表组成一个索引序列,同时列出数据和数据下标
 8             print(index, item)                  #index 为索引下标
 9         numbres = input("输入购买商品的序号:")
10         #if numbres !='q' and  numbres !='Q':
11         if numbres.isdigit():
12             numbres = int(numbres)                  #把一个字符转换成数字
13             if numbres< len(goods) and numbres >=0:  #判断输入的序号(索引下标),是否有该对应的商品
14                 money = int(money)
15                 numbres_goods=goods[numbres][1]        #列表切片,只取商品价格的字段
16                 if money >= numbres_goods:
17                     money=money-numbres_goods
18                     mgoods.append(goods[numbres])       #把用户买过的商品存放在一个新的列表里
19                     print('购买商品成功:'+goods[numbres][0])
20                     print('剩余金钱:\033[31;1m %s \33[0m' % money )
21                 else:
22                     print('余额不足!')
23         elif numbres=='q' or numbres=='Q':
24             print('你购买的商品如下:')
25             for i in mgoods:
26                 print(i)
27             break
28         else:
29             print('输入错误!!')
30 else:
31     print('输入错误!!,重新输入')

 


 




学习无止境,加油

 
posted @ 2020-03-01 14:24  Kong-Ming  阅读(409)  评论(0编辑  收藏  举报