購物車程序

 項目名稱:購物車程序
項目要求:
1.要求輸入用戶的工資,而後打印購物的菜單
2.用戶能夠不斷的購買商品直到錢不夠爲止
3.退出時格式化用戶已購買商品和所剩的餘額
  

  對於此項目我主要利用了字典的優勢。
程序流程圖:

 

項目代碼:iphone

 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()
相關文章
相關標籤/搜索