购物车程序需求:
启动程序后,让用户输入工资,然后打印商品列表;
允许用户根据商品编号购买商品;
用户选择商品后,检验余额是否够,不够就提醒;
可随时退出,退出时打印已购买商品和余额。

点击查看代码
product_list = [
    ('Iphone',5800),
    ('Mac Pro',9800),
    ('Bike',800),
    ('Watch',10600),
    ('Coffee',31),
    ('Alex Python',120)
]
shopping_list=[]
salary = input('Input your salary:')
if salary.isdigit():    #判断用户输入是否为数字类型
    salary = int (salary)
    while True:
        for index,item in enumerate(product_list):
            print(index,item)     #打印商品列表,取下标
        #用户选择购买什么东西
        user_choice=input('Enter the number of the item you want to buy:')
        #判断用户输入的是否为数字,若为数字转换成int()类型
        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))   #\033[31;1m%s\033[0m'  颜色  31:红色   32:绿色
                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')
else:   #用户输入不是数字
    print('你输入的不是数字!')

此随笔仅为自己巩固python学习内容

posted on 2022-01-24 18:07  寒梅煮雪  阅读(49)  评论(0)    收藏  举报