元组与购物车程序练习

元组其实和列表差不多,也是存一组数,只不过它一旦创建,便不能再修改,所以又叫只读列表

 

product_list = [
    ('iphone',5800),
    ('mac pro',9800),
    ('bike',800),
    ('watch',10600),
    ('coffee',31),
    ('alex python',120),
]
shopping_list = []

salary = input("请输入您的工资:")  #输入工资
if salary.isdigit():   #判断工资是不是数字
    salary = int(salary)  #将工资转为int类型
    while True:
        for index,item in enumerate(product_list):  #打印商品列表,enumerate方法是把下标取出来
            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)  #买得起,添加到shopping_list里
                    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")

 

posted @ 2017-08-15 17:37  _Cohen  阅读(139)  评论(0)    收藏  举报