Python--作业完成购物车功能

goods = [
    {"name":"电脑","price":"2000"},
    {"name":"鼠标","price":"20"},
    {"name":"键盘","price":"124"},
    {"name":"鼠标垫","price":"6"},
    {"name":"硬盘","price":"400"},
]
in1 = input("请输入您的资产:")
print("您的余额:"+in1+"$")
allgou = 0
isg = "y"
inum = 1
gCar = {}
while isg == "y":
    print("-------可选择的商品列表---------")
    for i,element  in enumerate(goods,1):
        print("商品编号"+str(i)+"商品名称:"+element["name"]+"********商品价格:"+element["price"])
    gl = input("请输入您想购买的商品编号:")
    gl = int(gl) - 1
    print(goods[gl]["name"]+"已经加入您的购物车")
    gname = str(inum)+goods[gl]["name"]
    inum +=1
    gCar[gname] = goods[gl]["price"]
    allgou = allgou+int(goods[gl]["price"])
    print("您当前的购物车列表:")
    for gc in gCar.items():
        print(gc)
    isg = input("请问您需要继续购买商品吗:y/n")

isq = input("需要清空购物车吗?总金额为:"+str(allgou)+"y/n")
if isq == "y":
    gCar = {}
    in1 = int(in1)-allgou
    if in1>=0:
        print("您账户的当前余额为:"+str(in1))
        print("欢迎购物!")
    else:
        isny = input("您的余额不足,是否充值y/n")
        if isny == "y":
            newmoney = input("请输入充值金额:")
            newmoney2 = int(newmoney)+int(in1)
            isq2 = input("需要清空购物车吗?总金额为:" + str(allgou) + "y/n")
            if isq2 == "y":
                newmoney2 = newmoney2 - allgou
                if newmoney2>=0:
                    print("购物成功!"+"您的余额为:"+str(newmoney2))
                else :
                    print("金额不足,购物失败!")
        else:
            print("购物失败!")

运行结果:

请输入您的资产:50000
您的余额:50000$
-------可选择的商品列表---------
商品编号1商品名称:电脑********商品价格:2000
商品编号2商品名称:鼠标********商品价格:20
商品编号3商品名称:键盘********商品价格:124
商品编号4商品名称:鼠标垫********商品价格:6
商品编号5商品名称:硬盘********商品价格:400
请输入您想购买的商品编号:1
电脑已经加入您的购物车
您当前的购物车列表:
('1电脑', '2000')
请问您需要继续购买商品吗:y/ny
-------可选择的商品列表---------
商品编号1商品名称:电脑********商品价格:2000
商品编号2商品名称:鼠标********商品价格:20
商品编号3商品名称:键盘********商品价格:124
商品编号4商品名称:鼠标垫********商品价格:6
商品编号5商品名称:硬盘********商品价格:400
请输入您想购买的商品编号:1
电脑已经加入您的购物车
您当前的购物车列表:
('1电脑', '2000')
('2电脑', '2000')
请问您需要继续购买商品吗:y/ny
-------可选择的商品列表---------
商品编号1商品名称:电脑********商品价格:2000
商品编号2商品名称:鼠标********商品价格:20
商品编号3商品名称:键盘********商品价格:124
商品编号4商品名称:鼠标垫********商品价格:6
商品编号5商品名称:硬盘********商品价格:400
请输入您想购买的商品编号:1
电脑已经加入您的购物车
您当前的购物车列表:
('1电脑', '2000')
('2电脑', '2000')
('3电脑', '2000')
请问您需要继续购买商品吗:y/nn
需要清空购物车吗?总金额为:6000y/ny
您账户的当前余额为:44000
欢迎购物!

注意问题

1、控制台输入的int类型,在进行数字操作的时候,要进行强制转换成int(),系统默认输入的是str

2、enumerate()方法的使用,在循环中增加一个序号,便于标识每一列的数据

3、注意字典,dict新增数据的时候。gCar[gname] = goods[gl]["price"]

 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值