1. 程式人生 > >基於Python語言實現的購物車程式<入門小白>

基於Python語言實現的購物車程式<入門小白>

1.需求:
1:啟動程式後,讓使用者輸入工資,然後列印商品列表
2:允許使用者根據商品編號購買商品
3:使用者選擇商品後,檢測餘額是否夠,夠就直接付款,不夠就提醒
4:可隨時推出,推出時,列印已購買商品和餘額

2.程式碼如下:

__author__ = "B J"


product_list = [
    ('Iphone',5800),
    ('Mac Pro',9800),
    ('Bike',800),
    ('Watch',10600),
    ('Coffee',31),
]
shopping_list = []
salary = input("Input your salary:
") if salary.isdigit(): salary = int(salary) while True: for index,item in enumerate(product_list): #print(product_list.index(item),item) print(index,item) user_choice = input("選擇要買嘛?>>>:") 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 -= p_item[1]
print("Added %s into shopping cart,your current balance is \033[31;1m%s\033[0m" %(p_item,salary) ) else: print("\033[41;1m你的餘額只剩[%s]啦,還買個毛線\033[0m" % salary) 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: