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

  

转载于:https://www.cnblogs.com/rdchenxi/p/11088684.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值