要求實現功能:
啓動程序後,用戶輸入工資,而後打印商品列表
容許用戶根據商品編號購買商品
用戶選擇商品後,檢測餘額是否夠,夠就直接扣款,不夠就提醒
可隨時退出,退出時, 打印已購買商品和餘額
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)]git
可是不影響購買app