python(4)- 简单练习:python实现购物车的优化

购物车程序优化题目要求:

    1. 用户退出时打印商品列表时,按以下格式

        -------您购买的商品如下------

        id    商品    数量    单价    总价

        1      iPhone 2      5800     11400

        2      coffee  1      30      30

        ...

        总计价格: 11430元

        --------end -------------

salary=int(input("please input your salary:"))      #输入薪资
product_list=[["iphone", 5888],                       #定义商品列表
             ["coffee",30],
             ["bike",299],
             ["vivo x9",2499],
             ["cake",40],
             ["book",99]]
product_cart={}           #定义购物车字典
total_cost= 0         #定义总花销
while True:              #循环打印可购买商品列表及退出提示
    print("可购买的商品")
    for number in range(len(product_list)):
        product = product_list[number]
        print(number,product)
    print("q","quit")

    choice=input("输入你所选择的商品编号>>:").strip()     #输入选择的商品编号或退出“q”
    if choice.isdigit():                                    #判断输入的是否为整数
        choice=int(choice)
        if choice < len(product_list) and choice >= 0:      #判断输入的数字是否商品编号范围内
            product=product_list[choice]                     #定义要买的商品列表
            if salary -product[1] >=0:                       #判断是否买的起
                salary-=product[1]                           #买的起自动结算
                print("将商品",product[0],"加入购物车,","你目前还有余额",salary,"元")   #输出当前本次操作信息及余额

                if product[0] in product_cart:               #判断购买的商品是否在购物车里
                    product_cart[product[0]][1]+=1           #在购物车里,则商品对应的数量+1
                else:                                        #不在购物车里,则将商品信息,商品单价,数量加入购物车内
                    product_cart[product[0]]=[product[1],1]
                print("目前你的购物车",product_cart)
            else:            #买不起则打印当前余额及差的金额。结束本次循环,重新开始循环,打印可购买商品列表及退出提示
                print("你目前还有余额", salary, "元,", "还差", product[1] - salary, "元")
        else:                         #输入的数字不在商品编号范围内,返回上一循环,打印可购买商品列表及退出提示
            print("商品不存在!")
    elif choice== "q":                #输入的不是数字为字符串“q”,打印已购买商品信息及总花销
        print("---------你购买的商品如下---------")
        print("id","	","商品","	","数量","	","单价","	","总价")
        id_counter=1                        #定义购买车商品编号
        for key in product_cart:
           print(id_counter,"	",           #依序打印购物车商品编号,商品,数量,单价及总价
                 key,"	",
                 product_cart[key][1],"		",
                 product_cart[key][0],"	",
                 product_cart[key][1]*product_cart[key][0])
           id_counter+=1
           total_cost+=product_cart[key][1]*product_cart[key][0]          #定义总花销
        print("总计价格为",total_cost)
        print("------------end------------")
        break                                                          #跳出循环

    else:             #输入的既不是整数,也不是字符串“q”,提示信息错误
        print("你输入的是什么鬼?")

  


运行程序结果为:









原文地址:https://www.cnblogs.com/xuyaping/p/6639850.html