[terry笔记]python购物程序

如下是一个购物程序:

先输入工资,显示商品列表,购买,quit退出,最后格式化输出所买的商品。

 1 count = 0
 2 while True:     #做一个循环判断,如果输入的不是数字,基于提示,三次后退出
 3     salary = input("input your salary:") #输入你的工资
 4     if salary.isdigit():  #输入的工资必须是数字才能往下走
 5         salary=int(salary)  #转换为整数型
 6         break
 7     else:
 8         print("Please input a number:")
 9         count += 1
10         if count == 3:
11             exit()
12 
13 goods_list = [["Iphone",5800],["Macbook",12800],["iMac",15000],["ApplePen",500],["IPod",1200]]  #商品列表
14 shop_list = []  #购买的商品列表
15 msg = " Product List "
16 print(msg.center(30,"*"))
17 for i,ele in enumerate(goods_list): #遍历序列中的元素以及它们的下标
18     print(i,".",ele[0],ele[1])
19 while True:
20     choice = input("Which do you want(quit type \"quit\")>>>")
21     if choice.isdigit():   #判断选择的是否是数字
22         choice = int(choice)   #转换为整数型
23         if choice <= len(goods_list)-1:  #选择的数字必须小于列表长度-1,因为下标从0开始
24             if salary >= int(goods_list[choice][1]):  #判断工资是否够
25                 shop_list.append(goods_list[choice])  #够的话,把商品加入到shopList
26                 salary -= goods_list[choice][1]  #减去工资
27                 print("You just buy a %s now you have %s RMB" % (goods_list[choice][0],salary))
28             else:
29                 print("Not enough money")
30         else:
31             print("There is no such things")
32     elif choice == "quit":
33         print("Here is what you buy:")  #这里的思路是,创建一个字典,把所买的商品格式化输出
34         total = 0
35         shop_dict={}
36         for item in shop_list:
37             things = item[0]
38             money = item[1]
39             total += int(money)
40             if things in shop_dict:
41                 shop_dict[things][0] += 1
42                 shop_dict[things][1] += money
43             else:
44                 shop_dict[things]=[1,money]
45         for item in shop_dict.items():
46             print("%s  %s个  共%s" % (item[0],item[1][0],item[1][1]))
47         print("一共花了:",total)
48         exit()
49     else:
50         print("Please input a number")
51         continue

 

转载于:https://www.cnblogs.com/kkterry/p/6002082.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值