William126

Python实战之实现简单的购物车系统

#!usr/bin/env Python3
# -*-coding:utf-8-*-

# 程序:购物车程序
#
# 需求:
#
#     启动程序后,让用户输入工资,然后打印商品列表
#     允许用户根据商品编号购买商品
#     用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
#     可随时退出,退出时,打印已购买商品和余额

__author__="William"
#定义一个shop类
class Shop(object):
    def __init__(self):
        #初始化,用户的money,商品单价
        self.salary = 0
        self.apple = 2
        self.banana = 3
        self.demo = 2.5
    #定义一个goods_list方法,用于展示商品及价格
    def goods_list(self):
        goods_list = ['apple','banana','demo']
        apple_price = self.apple
        banana_price = self.banana
        demo_price = self.demo
        print(goods_list[0],":",apple_price)
        print(goods_list[1], ":", banana_price)
        print(goods_list[2], ":", demo_price)
    #定义一个buy方法
    def buy(self):
        buy_list = []
        # 定义一个字典,用与用户选择
        goods_dict = {
            '1':'apple',
            '2':'banan',
            '3':'demo',
            '4':'quit'
        }
        while True:
            print(goods_dict)
            key = input("Please input your choose:>>>")
            if goods_dict[key] == 'quit':
                break
            else:
                if goods_dict[key] == 'apple':
                    buy_list.append('apple')
                    continue
                elif goods_dict[key] == 'banan':
                    buy_list.append('banan')
                    continue
                elif goods_dict[key] == 'demo':
                    buy_list.append('demo')
                    continue
                else:
                    print("Wrong input num")
        #计算商品总价个
        total = float(buy_list.count('apple')) * self.apple + float(buy_list.count('demo')) * self.demo + float(buy_list.count('banana')) * self.banana
        left = float(self.salary) - total

        print(total,",",left)


if __name__=="__main__":
    #实例化
    c1 = Shop()
    #初始化salary的值
    c1.salary = input("Please input your money:>>>")
    #分别调用good_list和buy方法
    c1.goods_list()
    c1.buy()

 

posted on 2017-06-23 15:02  William126  阅读(381)  评论(0编辑  收藏  举报

导航