购物车程序

                                                         项目名称:购物车程序
项目要求:
1.要求输入用户的工资,然后打印购物的菜单
2.用户可以不断的购买商品直到钱不够为止
3.退出时格式化用户已购买商品和所剩的余额
  

  对于此项目我主要利用了字典的优点。
程序流程图:

项目代码:

 1 #encoding=utf-8
 2 __author__ = 'heng'
 3 """
 4 ---------------------------------------------------------------------------------
 5 项目名称:购物车程序
 6 项目要求:
 7 1.要求输入用户的工资,然后打印购物的菜单
 8 2.用户可以不断的购买商品直到钱不够为止
 9 3.退出时格式化用户已购买商品和所剩的余额
10 
11 ---------------------------------------------------------------------------------
12 """
13 import sys
14 #购物车,用于存放购买成功的商品
15 shopping_cart = {}
16 #打印商品的种类和价格
17 the_goods = {'bike':999,
18              'milk':80,
19              'car':19999,
20              'iphone':5000,
21              'ipad':3000,
22              'ituch':1000,
23              'iwatch':400,
24              'macbook':9000
25 }
26 print 'the goods and price :'
27 #将字典中的信息全部打印出来
28 for i in the_goods:
29     print i,':',the_goods[i]
30 the_money = float(raw_input('please enter your money:'))
31 the_priece = 0  #用来统计购买商品的数量
32 while True:
33     print 'You can buy:'
34     i = 0
35 #判断可以支付的商品种类
36     for j in the_goods:
37         if the_goods[j] <= the_money:
38             i+=1
39             print j,':',the_goods[j]
40     if i==0:
41         print "You don't have enough money,you can buy nothing!go home man!"
42 #用户是否继续购物
43     if_leave = raw_input("DO you want to buy continue?y/n")
44     if if_leave == 'y':
45         want_buy = raw_input("please enter the goods you want to buy:")
46         #判断输入的是否正确
47         if want_buy not in the_goods.keys():
48             print "the goods can't find!"
49         else:
50             if the_goods[want_buy] <= the_money:       #判断用户是否可以支付
51                 if want_buy in shopping_cart:          #用来计算购买的数量
52                     shopping_cart[want_buy][1]+=1
53                 else:
54                       shopping_cart[want_buy] = [the_goods[want_buy],1]
55                 the_money = the_money - the_goods[want_buy]
56                 print "you buy %s succeed!"%want_buy
57             else:
58                 print "the good is too expensive for you ,you don't have enough money !"
59 
60             print "your balance is : %.2f"%the_money
61     else:
62         print "you had buy:"
63         for k in shopping_cart:     #输出购物车中的物品和数量
64             print shopping_cart[k][1],'piece ',k
65         print "your balance is : %.2f"%the_money
66         sys.exit()

腾飞前的蛰伏
原文地址:https://www.cnblogs.com/xiaoli2018/p/4474582.html