1. 程式人生 > >購物車實現

購物車實現

isdigit digi -s oob 用戶 就是 lan hone sdi

需求:
啟動程序後,讓用戶輸入工資,然後打印商品列表
允許用戶根據商品編號購買商品
用戶選擇商品後,檢測余額是否夠,夠就直接扣款,不夠就提醒
可隨時退出,退出時,打印已購買商品和余額


#Author:liubin
goods_list=[(‘iphone‘,5000),
            (‘clothing‘,1000),
            (‘book‘,100),
            (‘coffee‘,50),
            (‘tea‘,200),
            ]
shopping_list = []
salary = input("Input your salary:")
if salary.isdigit():   #Python isdigit() 方法檢測字符串是否只由數字組成。
    salary = int(salary)  #如果工資是數字,使用int
    while True:
        for index,item in enumerate(goods_list):   #http://www.runoob.com/python/python-func-enumerate.html一句話就是把下標取出來
            #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(goods_list) and user_choice >=0:
                p_item = goods_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:
            print("Invalid option")

購物車實現