1. 程式人生 > >python實戰小程式之購物車

python實戰小程式之購物車


# Author:南郵吳亦凡


# 商品列表
product_list = [
    ('Iphone',5800),  # 逗號一定不可以省略!
    ('Mac',4800),
    ('smartphone',400),
    ('watch',9100),
    ('coffee',500),
    ('python',9200),
]
shopping_list = []

# 工資
salary = input("Input your salary:")  # 輸入的是字串
if salary.isdigit():   # 如果這是一個數字,就轉成數字
    salary = int(salary)
    while True:
        # for item in product_list:
            print(item)                           # 無序號
        # for item in product_list:
            print(product_list.index(item),item)  # 有序號(1)

        for index,item in enumerate(product_list):
            print(index,item)                     # 有序號(2)

# 選擇買的商品
        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))
                    # print("Added %s into shopping cart,your current balance is %s" %(p_item,salary))  # 餘額沒有顏色
                else:    # 買不起
                    print("\033[41;1m你的餘額只剩[%s]啦\033[0m" % salary)  # 31無背景的紅色,41有背景的紅色
            print("商品[%s]不存在")
        elif user_choice =='q':
            print("-----shopping list------")
            for p in shopping_list:
                print(p)
            print("your current balance:",salary)
            exit()
        else:
            print("invalid option")

在這裡插入圖片描述