標籤:class ade 根據 art cart 輸入 使用者 檢測 user
要求實現功能:
啟動程式後,使用者輸入工資,然後列印商品列表
允許使用者根據商品編號購買商品
使用者選擇商品後,檢測餘額是否夠,夠就直接扣款,不夠就提醒
可隨時退出,退出時, 列印已購買商品和餘額
product_list = [ (‘iphone‘, 8100),
(‘mac pro‘, 13000),
(‘sea food‘, 600),
(‘bed‘, 3200),
(‘chair‘, 123),
(‘blue tooth header‘, 1800)
]
shopping_list = []
salary = input("please input your salary here: ")
if salary.isdigit(): #判斷工資是不是數字
salary = int(salary) #工資是數字,把salary類型變成int
while True: #進入迴圈
for index, item in enumerate(product_list):
print(index, product_list)
user_choice = input("please put number to choice what you want>>>>>>:")
if user_choice.isdigit(): #判斷使用者輸入必須是數字
user_choice = int(user_choice)
if user_choice < len(product_list) and user_choice >= 0: #使用者選擇的數字小於product list長度 且大於等於0
p_item = product_list[user_choice]
if p_item[1] <= salary:
shopping_list.append(p_item) #shopping list 裡增加該item
salary -= p_item[1] #購買物品後在工資裡扣除相應的錢
print("you have added %s into your shopping cart, and your current balance is: \033[31;1m%s\033[0m" %(p_item,salary))
# \033[31;1m%s\033[0m 字型顏色改成紅色
else:
print("\033[31;1m you don‘t have enough salary!\033[0m")
else:
print("%s is no exist option!" %user_choice)
elif user_choice == ‘q‘:
print("----------------your shopping list---------------")
for p in shopping_list:
print(p)
print(" your current balance is:", salary)
exit()
else:
print("invalid option")
使用 for index, item in enumerate(product_list)使 product_list更加靈活,後期可增加刪除裡面元素並且不影響原有代碼
註: 在list列印出來的時候是這樣的:(尚未解決)
0 [(‘iphone‘, 8100), (‘mac pro‘, 13000), (‘sea food‘, 600), (‘bed‘, 3200), (‘chair‘, 123), (‘blue tooth header‘, 1800)]
1 [(‘iphone‘, 8100), (‘mac pro‘, 13000), (‘sea food‘, 600), (‘bed‘, 3200), (‘chair‘, 123), (‘blue tooth header‘, 1800)]
2 [(‘iphone‘, 8100), (‘mac pro‘, 13000), (‘sea food‘, 600), (‘bed‘, 3200), (‘chair‘, 123), (‘blue tooth header‘, 1800)]
3 [(‘iphone‘, 8100), (‘mac pro‘, 13000), (‘sea food‘, 600), (‘bed‘, 3200), (‘chair‘, 123), (‘blue tooth header‘, 1800)]
4 [(‘iphone‘, 8100), (‘mac pro‘, 13000), (‘sea food‘, 600), (‘bed‘, 3200), (‘chair‘, 123), (‘blue tooth header‘, 1800)]
5 [(‘iphone‘, 8100), (‘mac pro‘, 13000), (‘sea food‘, 600), (‘bed‘, 3200), (‘chair‘, 123), (‘blue tooth header‘, 1800)]
但是不影響購買
python 購物車