用python编写购物程序(2)

要求:

  1. 启动程序后,让用户输入工资,然后打印商品列表
  2. 允许用户根据商品编号购买商品
  3. 用户选择商品后,检测余额是否充足,够就直接扣款,不够就提醒
  4. 可随时推出,退出时打印以购买商品,购买商品数量及余额

代码:

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 # Author:James Tao
 4 
 5 list_of_goods=[
 6     ['iphone',5800],
 7     ['Mac Pro',12000],
 8     ['Bike',800],
 9     ['Watch',2000],
10     ['Coffee',31],
11     ['Book',120]
12 ]
13 list_of_bought=[]
14 dict_of_bought={}
15 salary=input('请输入您的工资:')
16 if salary.isdigit():#判断是否是整数
17     salary=int(salary)
18     while True:
19 
20         #输出商品及其编号
21         for index,item in enumerate(list_of_goods):#enumerate取出下标
22             print(index,item)
23             #print(list_of_goods.index(item),item)
24         choice_of_user=input('选择购买商品编号:')
25 
26         #判断输入是否合法
27         if choice_of_user.isdigit():
28             choice_of_user=int(choice_of_user)
29 
30             #判断编号是否有对应商品
31             if 0<=choice_of_user<len(list_of_goods):
32 
33                 #判断余额是否足够买此商品
34                 if list_of_goods[choice_of_user][1]<=salary:
35 
36                     #加入购物清单
37                     list_of_bought.append(list_of_goods[choice_of_user][0])
38 
39                     #计算余额`
40                     salary-=list_of_goods[choice_of_user][1]
41 
42                     print('''添加{boughtgood}到您的购物车,此刻您的余额为{balance}.
43                     '''.format(boughtgood=list_of_goods[choice_of_user][0],balance=salary))
44                 else:
45                     print('您的余额不足,此实余额为%s,不够购买此商品',salary)
46             else:
47                 print('商品不存在')
48 
49         elif choice_of_user=='q':
50 
51             #统计购买的商品及数量
52             category_of_bought=set(list_of_bought)
53             for item in category_of_bought:
54                 dict_of_bought[item]=list_of_bought.count(item)
55             print('您购买的商品及数量分别为',dict_of_bought)
56 
57             print('您的余额为:',salary)
58             exit()
59         else:
60             print('输入不合法')
61 else:
62     print('输入不合法')

 

转载于:https://www.cnblogs.com/BIT-taozhen/p/9735865.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值