1. 程式人生 > >購物車程式碼(python2.7)

購物車程式碼(python2.7)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#__authot__ = yangdanhua
#shopping model


#購物車品類
product_list = [('iphone 8',7000),
                ('iphone 7',6000),
                ('iphone 6',5000),
                ('iphone se',4500),
                ('Mac pro',10050),
                ('iphone X',9000)]

#輸入用於購買的金額
salary = raw_input('please input your salary:'
) shopping_list=[] #判斷輸入金額是否為數字 if salary.isdigit(): salary = int(salary) #if內部迴圈 while True: for product in product_list: #迴圈輸出所有品類,每次判斷都要重新列印一遍 print ('\033[34;1m%s,%s,%s\033[0m'%(product_list.index(product),product[0],product[1])) product_choice = raw_input('please choice one product:'
) #輸入選擇產品編號 if product_choice.isdigit(): #判斷輸入字元型別是否正確 product_choice = int(product_choice) #型別強轉 if product_choice<len(product_list) and product_choice>=0: #判斷輸入是否在範圍內 product_item = product_list[product_choice] if product_item[1]<=salary: #判斷剩下的錢還夠不夠買東西
shopping_list.append(product_item[0]) #把購買的資訊存一下,待會會有清單 salary -= product_item[1] print ('added \033[31;1m%s\033[0m into shopping cart,your currant balance is \033[31;1m%s\033[0m'%(product_item[0],salary)) else: print('\033[31;1myour balance is not enough\033[0m') else: print ('\033[42;1mproduct is not exist,please choise again\033[0m') elif product_choice == 'q' or 'Q': #若輸入的'q' or 'Q'則自動退出 print ('\033[35;1m-------------shopping list-------------\033[0m') for i in shopping_list: print ('\033[31;1m%s\033[0m'%i) print 'salary:','\033[31;1m%s\033[0m'%salary break else: print('\033[36;1minvlid digit,please input again\033[0m') #輸入金額部位數字則提示輸入錯誤 else: print('\033[41;1minvlid digit,please input again\033[0m')