zoukankan      html  css  js  c++  java
  • Python作业之购物车

                                                      作业之购物车

    购物车的要求如下:

    1. 输入总金额
    2. 选择购买的商品,金额足够时,把选择的商品添加到购物车,金额不足时,进行提示,商品将不会添加到购物车
    3. 随时可以退出程序,同时输出已购买的商品

    具体代码如下:

    commoditys = [['pen',3],['bike',600],['pad',3000],['iphone',6000],['computer',5000],]#声明所有商品的列表
    shopping_car = []#声明一个空列表作为购物车
    money = input('请输入你的金额:').strip()#输入总金额,并对字符串进行两边去空格
    if money.isdigit():#判断输入的字符串是否是纯数字
        money = int(money)#把字符串类型的数字转换为int类型
        while True:#声明一个循环
            for index,commodity in enumerate(commoditys,1):#使用枚举函数遍历商品总列表
                print(index,'33[34m%s33[0m'%commodity[0],'33[31m%s33[0m'%commodity[1])#打印商品明细并指定输出的颜色
            print('选择Q或者q时,将退出程序!')
            choice = input('请选择你要购买的商品编号:').strip()
            if choice.isdigit():#判断输入的字符串是否是纯数字
                if int(choice) in range(1,6):#判断输入的数字是否在1-6的范围内,不包括6
                    if money >= commoditys[int(choice)-1][1]:#判断金额是否大于选择的商品价格
                        money -= commoditys[int(choice)-1][1]#总金额减去已经选择的商品的价格
                        shopping_car.append(commoditys[int(choice)-1])#把已选择的商品加入到购物车列表中
                        print('商品33[34m%s33[0m已经加入到购物车!'% commoditys[int(choice)-1][0])
                        print('您的余额为33[31m%s33[0m元!'% money)
                        continue
                    else:
                        print('您的余额不足以购买该商品,请选择其他商品!')
                        continue
                else:
                    print('您的输入有误,请重新输入!')
                    continue
            else:
                if choice == 'q' or choice == 'Q':
                    if bool(shopping_car) == True:#判断购物车列表是否是空的
                        print('购买商品明细表'.center(30,'*'))
                        for i in shopping_car:#遍历购物车列表的商品
                            print('商品为:33[34m%s33[0m,价格为:33[31m%s33[0m'% (i[0],i[1]))
                    else:
                        print('您本次并未消费!')
                    print('您的余额为33[31m%d33[0m元!欢迎下次光临!'% money)
                    print('程序已退出!')
                    break
                else:
                    print('您的输入有误,请重新输入!')
                    continue
    else:
        print('您输入的金额不对,程序已退出!谢谢您的使用!')
  • 相关阅读:
    验证字符串空“” 的表达式
    should not this be a private conversation
    【转】你真的了解word-wrap 和 word-break 的区别吗
    To live is to function,that is all there is in living
    [转] windows 上用程序putty使用 ssh自动登录Linux(Ubuntu)
    Vim/gvim容易忘记的快捷键
    [转] Gvim for windows中块选择的方法
    问题集
    web services
    Trouble Shooting
  • 原文地址:https://www.cnblogs.com/single-boy/p/7481537.html
Copyright © 2011-2022 走看看