优化之后的购物车小程序

# -*- coding: UTF-8 -*-
# Author linqiuci
# 需求:
# 1.启动程序后,让用户输入工资,然后打印商品列表
# 2.允许用户根据商品编号购买商品
# 3.用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
# 4.可随时退出,退出时,打印已购买商品和余额
# 定义商品列表
product_list = [('Iphone',5999),
                ('Ipad',2999),
                ('Applewatch',1999),
                ('Airpods2',1699),
                ('Book',99),
                ('SevenBus',29),
                ('Lucking coffe of latte',29)
                ]
shopping_list = [] # 创建一个空的购物列表
salary = input('---Please input your salary:')
if salary.isdigit(): # 判定输入的是否是整数
    salary = int(salary)
    while True:
        for index,p_item in enumerate(product_list): # 取product_list的下标
            print(index,p_item)
        user_chioce = input('---Please input product number:')
        if user_chioce.isdigit(): # 判定输入的是否是整数
            user_chioce = int(user_chioce)
            if user_chioce < len(product_list) and user_chioce >= 0: # 判定输入的数值是否合理
                product_chioce = product_list[user_chioce]
                if product_chioce[1] <= salary: # 判定是否买得起
                    shopping_list.append(product_chioce)
                    salary -= product_chioce[1] # 赋值运算符 等于 salary = salary - product_chioce[1]
                    print('Add %s to you shopping cart,your blanece have \033[31;1m %s \033[0m'%(shopping_list,salary)) # \033[31;1m %s \033[0m 文字高亮
                else:
                    print('Your salary is \033[42;1m %s\033[0m and not enough,please choice again'%(salary))
            else:
                print("Your choice doesn't exist")
        elif user_chioce == "q":
            print('------shopping list------')
            for s_item in shopping_list:
                print(s_item)
            print('Your blanece have %s'% (salary))
            exit()
        else:
            print("Your choice doesn't exist !!!")
else:
    print('You must input a number!')
posted @ 2021-10-01 22:12  小鹿乱撞_pyc  阅读(48)  评论(0)    收藏  举报