【python】簡單的購物車
阿新 • • 發佈:2017-11-20
python
#!/usr/bin/env python #-*- coding:utf-8 -*- #簡單的購物車 #知識點: #1:優雅的enumerate函數,返回一個生成器對象:(index,item)的元組 #2:print(‘product list :’.center(50,’-‘)) 可以居中打印,真好玩,哈哈 goods = [ ("IPhone",5800), ("watch",2000), ("mac",12000)] goods_cart = [] mybudget = raw_input("請輸入您的預算:") while not mybudget.isdigit(): mybudget = input("您的預算輸入有誤,請重新輸入.") mybudget = int(mybudget) while True: print "商品列表".center(50,‘-‘) print "編號".center(8,‘ ‘),"名稱".ljust(30,‘ ‘),"價格".ljust(12,‘ ‘) for i in enumerate(goods): #enumerate函數會返回下標和取值 print str(i[0]).center(6,‘ ‘),str(i[1][0]).ljust(28,‘ ‘),str(i[1][1]).ljust(12,‘ ‘) user_choose = raw_input("請輸入你的選擇:") if user_choose.isdigit(): user_choose = int(user_choose) if user_choose >=0 and user_choose <len(goods): #先判斷商品是否存在 if mybudget - goods[user_choose][1] > 0: #在判斷預算是否大於0 mybudget -= goods[user_choose][1] goods_cart.append(goods[user_choose]) #商品加入購物車 print "預算還有%d." %(mybudget) else: print "預算不夠了." else: print "商品不存在." elif user_choose == "q": break print "還剩預算%d" %(mybudget) print "購物車商品信息".center(50,"-") for i in enumerate(goods_cart): print str(i[0]).center(6, ‘ ‘), str(i[1][0]).ljust(28, ‘ ‘), str(i[1][1]).ljust(12, ‘ ‘)
效果圖
本文出自 “孔小發愛吃魚” 博客,謝絕轉載!
【python】簡單的購物車