用python编写购物程序,1

要求:

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

代码:

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 # Author:James Tao
 4 
 5 
 6 salary=int(input('请输入您的工资:'))
 7 list_of_goods=[['iphone',5800],['Mac Pro',12000],['Starbuck',31],['Bicycle',800]]
 8 print('支持购买的商品及价格:',list_of_goods)
 9 balance=salary
10 goods_of_bought=[]
11 goods_of_categorical={}
12 
13 judge=True
14 while balance>0 and judge:
15 
16     #打印出商品列表及编号
17     for i in range(len(list_of_goods)):
18         print('{goods}对应编号为:{n} \n'.format(goods=list_of_goods[i][0],n=i))
19 
20     number = int(input('请输入您要购买的商品编号:'))
21     #计算余额
22     balance=balance-int(list_of_goods[number][1])
23 
24     #判断余额是否为0
25     if balance>0:
26 
27         #将购买的商品加入购物车
28         goods_of_bought.append(list_of_goods[number][0])
29         quit1=input('继续购买?(Y?N):')
30         if quit1=='N':
31             judge=False
32 
33     else:
34 
35         #若余额小于0,将上一次购买的商品金额去除
36         balance = balance + int(list_of_goods[number][1])
37         quit2=input('余额不足,是否退出?(Y/N):')
38         if quit2=='Y':
39             judge=False
40 
41 #判断是否购买了商品
42 if goods_of_bought: #如果列表为空等于False
43 
44     #统计购买的商品种类
45     goods_of_set=set(goods_of_bought)
46 
47     #统计购买的商品数量并输出
48     for item in goods_of_set:
49         goods_of_categorical[item]=goods_of_bought.count(item)
50     print('您购买的商品及数量为:',goods_of_categorical)
51 
52 else:
53     print('您未购买任何商品')
54 
55 print('余额为:',balance)