zoukankan      html  css  js  c++  java
  • 【python练习】购物车程序

    购物车程序

    基本功能:

    1、使用用户名密码登陆

    2、允许用户根据商品编号购买商品

    3、用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒

    4、可随时退出,退出时,打印已购买商品和余额

    5、可以记录用户的消费记录,余额,在下次登陆的时候恢复

    6、允许查询之前的消费记录

    运行方法:
    文件执行、交互式执行。

    使用说明:
    测试账号(用户名:liubei,密码:lb123)

    用户数据:
    {"lock state": true, "account": "liubei", "password": "lb123", "balance": 993, "record": {"20180101": {"00:00:00": {"name": "u7535u8111", "price": 1999}, "23:01:02": {"name": "u9f20u6807", "price": 10}}, "20180202": {"00:02:00": {"name": "u7f8eu5973", "price": 998}}, "20180724": {"22:11:13": {"name": "u7535u8111", "price": 1999}, "22:11:14": {"name": "u9f20u6807", "price": 10}, "22:38:21": {"name": "u7535u8111", "price": 1999}, "22:40:32": {"name": "u7535u8111", "price": 1999}, "22:41:31": {"name": "u7535u8111", "price": 1999}, "22:41:35": {"name": "u9f20u6807", "price": 10}, "22:42:41": {"name": "u7535u8111", "price": 1999}, "22:42:43": {"name": "u9f20u6807", "price": 10}, "22:46:16": {"name": "u9f20u6807", "price": 10}, "22:56:56": {"name": "u9f20u6807", "price": 10}, "23:13:32": {"name": "u7535u8111", "price": 1999}}}}
    ..dataliubei
    
    
      1 #!/usr/bin/env python
      2 # -*- coding: utf-8 -*-
      3 
      4 '''
      5 测试账号(用户名:liubei,密码:lb123)
      6 '''
      7 
      8 import os,time
      9 import json
     10 
     11 goods = [
     12     {'name': '电脑', 'price': 1999},
     13     {'name': '鼠标', 'price': 10},
     14     {'name': '游艇', 'price': 20},
     15     {'name': '美女', 'price': 998}
     16 ]
     17 
     18 class Shopping(object):
     19     def __init__(self):
     20         self.acc_data = {} #用户信息
     21 
     22     def authentication(self):
     23         '''
     24         用户认证程序
     25         :return:登陆成功返回True
     26         '''
     27         acc = ''
     28         auth_list = []  # 用于存放每次输入的用户名
     29 
     30         print('- - - Login - - -')
     31         while auth_list.count(acc) < 3:  # 当相同的用户名登陆失败3次,跳出循环
     32             acc = input('Account:').strip()
     33             pwd = input('Password:').strip()
     34 
     35             path = 'data\%s' % acc  # 用户信息存放路径
     36             if os.path.isfile(path):  # 用户名是否存在
     37                 with open(path) as f:
     38                     self.acc_data = json.loads(f.read())    #读取信息
     39                     if self.acc_data['lock state']:  #用户是否被锁定
     40                         if self.acc_data['password'] == pwd:
     41                             print('Login success !')
     42                             return True
     43                         else:
     44                             auth_list.append(acc)
     45                             print('The password is error,you have %s times' % (3 - auth_list.count(acc)))
     46                     else:
     47                         print('You have tried 3 times,your account has locked.')
     48                         exit()
     49             else:
     50                 auth_list.append(acc)
     51                 print('The account is not exist...you have %s times' % (3 - auth_list.count(acc)))
     52 
     53         if auth_list.count(acc) == 3:  # 已存在的用户登陆失败三次,锁定,写入文件
     54             if os.path.isfile(path):
     55                 with open(path, 'w')as f:
     56                     self.acc_data['lock state'] = False
     57                     f.write(json.dumps(self.acc_data))
     58 
     59     def shopping(self):
     60         '''
     61         购物窗口
     62         :return:
     63         '''
     64         buy_dic = []
     65         while True:
     66             print('List of goods'.center(30,'-'))
     67             for index,item in enumerate(goods,1):
     68                 print('%s . 33[0;33m%s33[0m   33[0;32m%s33[0m'%(index,item['name'],item['price']))
     69             buy = input('("q" to exit)
    choose one to buy:').strip()
     70             if buy.isnumeric() and 0 < int(buy) <= len(goods): #输入是数字且在商品序号范围内
     71                 if self.acc_data['balance'] >= int(goods[int(buy) - 1]['price']):
     72                     self.acc_data['balance'] -= int(goods[int(buy) - 1]['price'])    #扣除余额
     73                     buy_dic.append(goods[int(buy) - 1]) #购物记录
     74                     #更新购物清单
     75                     localday = time.strftime('%Y%m%d', time.localtime())
     76                     localtime = time.strftime('%H:%M:%S', time.localtime())
     77                     if localday in self.acc_data['record']:
     78                         self.acc_data['record'][localday][localtime] = goods[int(buy) - 1]
     79                     else:
     80                         self.acc_data['record'][localday] = {localtime:goods[int(buy) - 1]}
     81                     #写入文件
     82                     if self.db_handle():
     83                         print('You have buy:33[0;32m%s33[0m'%goods[int(buy) - 1]['name'])
     84                     else:
     85                         print('33[0;31mSystem error...you have not buy %s33[0m'%goods[int(buy) - 1]['name'])
     86                 else:
     87                     print('33[0;33mYour balance can not afford anyone..33[0m')
     88             elif buy == 'q':
     89                 if len(buy_dic) != 0:
     90                     print('33[1;31;46mShopping receipts33[0m')
     91                     for index,item in enumerate(buy_dic,1):
     92                         print('%s . 33[0;33m%s33[0m   33[0;32m%s33[0m' % (index, item['name'], item['price']))
     93                 break
     94             else:
     95                 print('33[0;31minput error...33[0m')
     96 
     97     def recharge(self):
     98         '''
     99         充值
    100         :return:
    101         '''
    102         recharge = input('You want to recharge:').strip()
    103         if recharge.isnumeric() and int(recharge) < 0:
    104             print('33[0;31mPlease input a number greater than zero33[0m')
    105         elif recharge.isnumeric():
    106             self.acc_data['balance'] += int(recharge)
    107             if self.db_handle():
    108                 print('33[0;31mRecharge success !33[0m')
    109             else:
    110                 print('33[0;31mRecharge error...33[0m')
    111         else:
    112             print('33[0;31minput error...33[0m')
    113 
    114     def record(self):
    115         '''
    116         查询历史清单
    117         :return:
    118         '''
    119         for date in self.acc_data['record']:
    120             print('33[0;34m%s33[0m'%date.center(20, '-'))
    121             for time in self.acc_data['record'][date]:
    122                 print(time, ':', self.acc_data['record'][date][time]['name'],
    123                       self.acc_data['record'][date][time]['price'])
    124 
    125     def exit(self):
    126         '''
    127         退出函数
    128         :return:
    129         '''
    130         print('exit...')
    131         exit()
    132 
    133     def db_handle(self):
    134         '''
    135         文件写入
    136         :return:
    137         '''
    138         with open('data\'+self.acc_data['account'],'w') as f:
    139             f.write(json.dumps(self.acc_data))
    140             return True
    141 
    142     def interaction(self):
    143         '''
    144         交互
    145         :return:
    146         '''
    147         print(' Mall '.center(30, '*'))
    148         if self.authentication():    #登陆认证成功
    149             exit_flag = False
    150             while not exit_flag:
    151                 print('''
    Vip name:{account}
    Balance:33[1;31;46m{balance}33[0m
    
    1.  购物
    2.  充值
    3.  清单
    4.  退出
    152                 '''.format(account=self.acc_data['account'], balance=self.acc_data['balance']))
    153 
    154                 menu_dic = { #对应类方法的字典
    155                     '1': self.shopping,
    156                     '2': self.recharge,
    157                     '3': self.record,
    158                     '4': self.exit
    159                 }
    160                 user_option = input('>>>').strip()
    161                 if user_option in menu_dic:
    162                     menu_dic[user_option]()
    163                 else:
    164                     print('Without this option(%s)' % user_option)
    165 
    166 s = Shopping()    #实例化
    167 s.interaction()
  • 相关阅读:
    poj2679
    poj2709
    poj1521
    poj2054
    静脉曲张病案
    眩晕耳鸣病案
    声嘶治验
    甘露消毒丹治疗高热不退一例
    黄芩汤加减治疗腹痛一例
    自残症治愈案
  • 原文地址:https://www.cnblogs.com/q1ang/p/8870373.html
Copyright © 2011-2022 走看看