python 基础之简单购物车小程序实现

购物车

all_list = [
    ('mac',9000),
    ('kindle',900),
    ('tesla',800),
    ('python',105),
    ('bile',2000),
]
saving=input('输入资产:')
#判断用户是否输入数字i
shopping_car=[]  #
if saving.isdigit():
    saving=int(saving)
    # for i in all_list:
    while True:

        for i,v in enumerate(all_list):  #自己添加序号类  ,分别赋值
            # print(all_list.index(i)+1,i)
            print(i+1,'>>>>>',v) #展示商品列表
        choice=input('购买商品编号[退出q]:')
        if choice.isdigit():
            choice=int(choice)  #字符串转换数字
            if choice > 0 and choice<=len(all_list): #判断输入的超出范围
                p_item=all_list[choice-1]  #取出商品价格
                if p_item[1] < saving: #将商品价格与用户输入价格做比较
                    saving-=p_item[1] #将用户的输入的资产与商品价格相减,重新赋值给用户输入价格变量
                    shopping_car.append(p_item) # 将用户购买商品添加到,这个元素里
                else:
                    print('余额不足%s元:'%saving)#如果钱不够就显示钱不够

                print(p_item)
            else:
                print('编码不存在')#如果输入的不存在就直接显示不存在

        elif choice=='q':# 输入的q表示退出
            print('您购买如下商品')#并打印用户买的信息
            for i in shopping_car:
                print(i)
            print('您还剩余%s元:'%saving)#在打印出用户剩余的钱
            break

  测试

 

D:\python\python.exe D:/untitled/dir/for.py
输入资产:5000
1 >>>>> ('mac', 9000)
2 >>>>> ('kindle', 900)
3 >>>>> ('tesla', 800)
4 >>>>> ('python', 105)
5 >>>>> ('bile', 2000)
购买商品编号[退出q]:9
编码不存在
1 >>>>> ('mac', 9000)
2 >>>>> ('kindle', 900)
3 >>>>> ('tesla', 800)
4 >>>>> ('python', 105)
5 >>>>> ('bile', 2000)
购买商品编号[退出q]:2
('kindle', 900)
1 >>>>> ('mac', 9000)
2 >>>>> ('kindle', 900)
3 >>>>> ('tesla', 800)
4 >>>>> ('python', 105)
5 >>>>> ('bile', 2000)
购买商品编号[退出q]:3
('tesla', 800)
1 >>>>> ('mac', 9000)
2 >>>>> ('kindle', 900)
3 >>>>> ('tesla', 800)
4 >>>>> ('python', 105)
5 >>>>> ('bile', 2000)
购买商品编号[退出q]:5
('bile', 2000)
1 >>>>> ('mac', 9000)
2 >>>>> ('kindle', 900)
3 >>>>> ('tesla', 800)
4 >>>>> ('python', 105)
5 >>>>> ('bile', 2000)
购买商品编号[退出q]:q
您购买如下商品
('kindle', 900)
('tesla', 800)
('bile', 2000)
您还剩余1300元:

Process finished with exit code 0

  

posted @ 2019-06-26 11:03  烟雨楼台,行云流水  阅读(259)  评论(0编辑  收藏  举报