1. 程式人生 > >Python 練習1——簡易購物車

Python 練習1——簡易購物車

數字類型 數字 shopping enum off odi for in mac pro ping

簡易購物車用於了解購物車的大致原理,利用Python實現簡易購物車的基本功能,即:用戶將所選擇的商品放入購物車中,結算時自動輸出所購買商品及所剩余額。

# -*- coding: UTF-8 -*- 
product_list = [
(‘iphone‘,6000),
(‘Mac Pro‘,10000),
(‘bike‘,2000),
(‘Watch‘,16000),
(‘coffee‘,30),
(‘book‘,40)
]
shopping_list = []
salary = input("Input your salary:")
if salary.isdigit(): #isdigit判斷是否是一個整數數字,若是則會返回一個真(Ture)
salary = int(salary)
while True:
‘‘‘for item in product_list:
print(product_list.index(item),item) 這樣寫也是可以的,獲取下標作為產品的產品編號
‘‘‘
for index,item in enumerate(product_list):
print(index,item) #打印商品列表
user_choice = input("what choice your buying?")
if user_choice.isdigit(): #選擇數字類型
user_choice = int(user_choice)
if user_choice < len(product_list) and user_choice >= 0:
p_item = product_list[user_choice] #通過下標取商品
if p_item[1] <= salary:    #商品價格小於用戶余額,即能買得起
shopping_list.append(p_item)    
salary = salary - p_item[1]
print("Added %s into shopping cart,Your current balance is %s" %(p_item,salary))
else:
print("余額不足")
else:
print("product code [%s] is not exist!" % (user_choice))

elif user_choice == ‘q‘:
print(‘---------shopping list---------
‘)
for p in shopping_list:
print(p)
print("Your current balance:",salary)
exit()
else:
print("invalid option")

簡易購物車僅能實現靜態的商品列表。

Python 練習1——簡易購物車