使用Python3 编写简单信用卡管理程序


Posted in Python onDecember 21, 2016

1、程序执行代码:

#Author by Andy
#_*_ coding:utf-8 _*_
import os,sys,time
Base_dir=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(Base_dir)
str="欢迎使用银行信用卡自助服务系统!\n"
for i in str:
  sys.stdout.write(i)
  sys.stdout.flush()
  time.sleep(0.3)
while True:
  print("1、管理人员入口。")
  time.sleep(0.3)
  print("2、用户登录入口。")
  print("3、退出请按q!")
  choice=input(":")
  from core import main
  Exit_flag=True
  while Exit_flag:
    user_choice=main.menu(choice)
    if user_choice == '1':
      main.get_user_credit()
    elif user_choice == '2':
      main.repayment()
    elif user_choice == '3':
      main.enchashment()
    elif user_choice == '4':
      main.change_pwd()
    elif user_choice == '5':
      main.transfer()
    elif user_choice == '6':
      main.billing_query()
    elif user_choice == '7':
      print("该功能正在建设中,更多精彩,敬请期待!")
    elif user_choice == 'a':
      main.change_user_credit()
    elif user_choice == 'b':
      main.add_user()
    elif user_choice == 'c':
      main.del_user()
    elif user_choice == 'd':
      main.change_pwd()
    elif user_choice == 'q' or user_choice == 'Q':
      print("欢迎再次使用,再见!")
      Exit_flag = False

2、程序功能函数:

#Author by Andy#_*_ coding:utf-8 _*
import json,sys,os,time,shutil
Base_dir=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(Base_dir)
#定义认证装饰器
def auth(func):
  def wrapper(*args,**kwargs):
    # print("请输入卡号和密码进行验证!")
    f = open(Base_dir+'\data\\user_db.txt', 'r')
    Log_file = open(Base_dir+'\logs\log.txt', 'a+', encoding='utf-8')
    Bill_log_file = open(Base_dir + '\logs\\bill_log.txt', 'a+', encoding='utf-8')
    func_name = func.__name__
    Time_formate = '%Y-%m-%d %X'
    start_time = time.strftime(Time_formate, time.localtime())
    user_data = json.load(f)
    count=0
    while count < 3:
      global user_id
      global user_pwd
      user_id = input('请输入您的卡号:')
      user_pwd = input('请输入您的密码:')
      if user_id in user_data:
        if user_pwd == user_data[user_id]['Password']:
          Log_file.write(start_time + ' 卡号 %s 认证成功!\n' % user_id)
          Log_file.flush()
          time.sleep(1)
          Log_file.close
          keywords = func(*args, **kwargs)
          if func_name == 'repayment' or func_name == 'transfer' or func_name == 'enchashment':
            Bill_log_file.write(start_time + ' 卡号 '+ user_id + ' 发起 ' + func_name + ' 业务,金额为: %s \n' % keywords)
            Bill_log_file.flush()
            time.sleep(1)
            Bill_log_file.close
            return keywords
          else:
            return keywords
        else:
          print('卡号或密码错误!请重新输入!')
          Log_file.write(start_time + ' 卡号 %s 认证失败!\n' % user_id)
          Log_file.flush()
          time.sleep(1)
          Log_file.close
          count +=1
      else:
        print("卡号不存在,请确认!")
      if count == 3:
        print("对不起,您已输错3三次,卡号已锁定!")
        Log_file.write(start_time + ' 卡号 %s 因连续三次验证失败而被锁定!\n' % user_id)
        time.sleep(1)
        Log_file.close
  return wrapper
#定义菜单函数,根据不同用户显示不通菜单。
def menu(choice):
  if choice == '2':
    print( "请选择服务类别:\n"
       "1、查询信用额度。\n"
       "2、信用卡还款。\n"
       "3、信用卡提现。\n"
       "4、修改口令。\n"
       "5、信用卡转账。\n"
       "6、信用卡账单查询。\n"
       "7、轻松购物。\n"
       "8、退出请按q!\n")
    service_items = input('-->')
  elif choice == '1':
    print("请选择服务类别:\n"
       "a、修改用户信用额度。\n"
       "b、新增信用卡用户。\n"
       "c、删除信用卡用户。\n"
       "d、修改用户口令。\n"
       "e、退出请按q!\n")
    service_items = input('-->')
  else:
    print("感谢使用,祝生活愉快!")
    exit()
  return service_items
# 定义备份用户数据文件函数
def back_up_file():
  Time_formate = '%Y-%m-%d'
  Sys_time = time.strftime(Time_formate, time.localtime())
  shutil.copy(Base_dir + "\data\\user_db.txt", Base_dir + "\data\\user_db--" + Sys_time + ".bak.txt")
#定义获取用户数据信息函数
def get_user_data():
  with open(Base_dir + "\data\\user_db.txt", 'r+',encoding='utf-8') as f:
    user_data = json.load(f)
  return user_data
#定义用户数据变量
user_data = get_user_data()
#定义查询信用额度函数
@auth
def get_user_credit():
  user_credit=user_data[user_id]['Credit']
  print("您目前的信用额度为:%s元\n"
     %(user_credit))
  time.sleep(2)
  return user_credit
#定义信用卡还款函数
@auth
def repayment():
  user_data = get_user_data()
  user_credit=int(user_data[user_id]['Credit'])
  user_balance=int(user_data[user_id]['Balance'])
  user_bill = user_credit - user_balance
  print("您目前需要还款金额为:%s元.\n" %user_bill)
  Exit_flag=True
  while Exit_flag:
    repayment_value=input("请输入还款金额:")
    if repayment_value.isdigit():
      repayment_value=int(repayment_value)
      user_data[user_id]['Balance'] = user_data[user_id]['Balance'] + repayment_value
      f = open(Base_dir + "\data\\user_db.txt", 'r+', encoding='utf-8')
      json.dump(user_data, f)
      f.close()
      print("恭喜,还款成功!")
      print("您目前需要还款金额为:%s元.\n" % (user_data[user_id]['Credit'] - user_data[user_id]['Balance']))
      time.sleep(1)
      Exit_flag = False
      return repayment_value
    else:
      print("请输入正确的金额!")
#定义信用卡提现函数
@auth
def enchashment():
  user_credit=user_data[user_id]['Credit']
  print("你可用的取现额度为:%s" %user_credit)
  Exit_flag=True
  while Exit_flag:
    enchashment_value=input("请输入您要取现的金额:")
    if enchashment_value.isdigit():
      enchashment_value=int(enchashment_value)
      if enchashment_value % 100 == 0:
        if enchashment_value <= user_credit:
          user_data[user_id]['Balance'] = user_credit - enchashment_value
          f = open(Base_dir + "\data\\user_db.txt", 'r+', encoding='utf-8')
          json.dump(user_data, f)
          f.close()
          print("取现成功,您目前的可用额度为:%s" %user_data[user_id]['Balance'])
          time.sleep(1)
          Exit_flag = False
          return enchashment_value
        else:
          print("您的取现额度必须小于或等于您的信用额度!")
      else:
        print("取现金额必须为100的整数倍!")
    else:
      print("输入有误,取现金额必须为数字,且为100的整数倍")
@auth
#定义信用卡转账函数
def transfer():
  user_balance=user_data[user_id]['Balance']
  print("您目前的可用额度为:%s" %user_balance)
  Exit_flag=True
  while Exit_flag:
    transfer_user_id = input("请输入对方帐号:")
    transfer_value = input("请输入转账金额:")
    if transfer_user_id in user_data.keys():
      while Exit_flag:
        if transfer_value.isdigit():
          while Exit_flag:
            transfer_value=int(transfer_value)
            user_passwd=input("请输入口令以验证身份:")
            if user_passwd == user_data[user_id]['Password']:
              user_balance = user_balance- transfer_value
              user_data[transfer_user_id]['Balance']=int(user_data[transfer_user_id]['Balance']) + transfer_value
              f = open(Base_dir + "\data\\user_db.txt", 'r+', encoding='utf-8')
              json.dump(user_data, f)
              f.close()
              print("转账成功,您目前的可用额度为:%s" % user_balance)
              time.sleep(1)
              Exit_flag = False
              return transfer_value
            else:
              print("密码错误,请重新输入!")
        else:
          print("转账金额,必须为数字,请确认!")
    else:
      print("帐号不存在,请确认!")
# @auth
#定义信用卡账单查询函数
@auth
def billing_query():
  print("我们目前仅提供查询所有账单功能!")
  print("您的账单为:\n")
  Bill_log_file = open(Base_dir + '\logs\\bill_log.txt', 'r', encoding='utf-8')
  for lines in Bill_log_file:
    if user_id in lines:
      print(lines.strip())
  print()
  time.sleep(1)
 
#定义修改信用卡额度函数
def change_user_credit():
  print("您正在修改用户的信用额度!")
  Exit_flag=True
  while Exit_flag:
    target_user_id=input("请输入您要修改的用户卡号:\n")
    if target_user_id in user_data.keys():
      while Exit_flag:
        new_credit=input("请输入新的信用额度:\n")
        if new_credit.isdigit():
          new_credit= int(new_credit)
          user_data[target_user_id]['Credit']=new_credit
          print("卡号 %s 的新信用额度为:%s " %(target_user_id,new_credit))
          choice = input("确认请输入1或者按任意键取消:\n")
          if choice == '1':
            f = open(Base_dir + "\data\\user_db.txt", 'r+', encoding='utf-8')
            json.dump(user_data, f)
            f.close()
            print("信用额度修改成功,新额度已生效!")
            print("卡号 %s 的新信用额度为:%s " % (target_user_id, user_data[target_user_id]['Credit']))
            time.sleep(1)
            Exit_flag = False
          else:
            print("用户的信用额度未发生改变!")
        else:
          print("信用额度必须为数字!请确认!")
    else:
      print("卡号不存在,请确认!")
#定义修改口令函数
@auth
def change_pwd():
  print("注意:正在修改用户密码!")
  Exit_flag = True
  while Exit_flag:
    old_pwd = input("请输入当前密码:")
    if old_pwd == get_user_data()[user_id]["Password"]:
      new_pwd = input("请输入新密码:")
      new_ack = input("请再次输入新密码:")
      if new_pwd == new_ack:
        user_data=get_user_data()
        user_data[user_id]["Password"]=new_pwd
        f = open(Base_dir + "\data\\user_db.txt", 'r+', encoding='utf-8')
        json.dump(user_data, f)
        f.close()
        print("恭喜,密码修改成功!")
        time.sleep(1)
        Exit_flag = False
      else:
        print("两次密码不一致,请确认!")
    else:
      print("您输入的密码不正确,请在确认!")
#定义新增信用卡函数
def add_user():
  Exit_flag = True
  while Exit_flag:
    user_id = input("user_id:")
    Balance = input("Balance:")
    Credit = input("Credit:")
    if Balance.isdigit() and Credit.isdigit():
      Balance = int(Balance)
      Credit = int(Credit)
    else:
      print("余额和信用额度必须是数字!")
      continue
    Name = input("Name:")
    Password = input("Password:")
    print("新增信用卡用户信息为:\n"
       "User_id:%s\n"
       "Balance:%s\n"
       "Credit:%s\n"
       "Name:%s\n"
       "Password:%s\n"
       %(user_id, Balance, Credit, Name, Password))
    choice = input("提交请按1,取消请按2,退出请按q:")
    if choice == '1':
      back_up_file()
      user_data=get_user_data()
      user_data[user_id] = {"Balance": Balance, "Credit": Credit, "Name": Name, "Password": Password}
      f = open(Base_dir + "\data\\user_db.txt", 'w+', encoding='utf-8')
      json.dump(user_data, f)
      f.close()
      print("新增用户成功!")
      time.sleep(1)
      Exit_flag=False
    elif choice == '2':
      continue
    elif choice == 'q' or choice == 'Q':
      time.sleep(1)
      Exit_flag = False
    else:
      print('Invaliable Options!')
#定义删除信用卡函数
def del_user():
  Exit_flag = True
  while Exit_flag:
    user_id=input("请输入要删除的信用卡的卡号:")
    if user_id == 'q' or user_id == 'Q':
      print('欢迎再次使用,再见!')
      time.sleep(1)
      Exit_flag=False
    else:
      user_data=get_user_data()
      print("新增信用卡用户信息为:\n"
         "User_id:%s\n"
         "Balance:%s\n"
         "Credit:%s\n"
         "Name:%s\n"
         % (user_id, user_data[user_id]['Balance'], user_data[user_id]['Credit'], user_data[user_id]['Name']))
      choice = input("提交请按1,取消请按2,退出请按q:")
      if choice == '1':
        back_up_file()
        user_data.pop(user_id)
        f = open(Base_dir + "\data\\user_db.txt", 'w+',encoding='utf-8')
        json.dump(user_data, f)
        f.close()
        print("删除用户成功!")
        time.sleep(1)
        Exit_flag = False
      elif choice == '2':
        continue
      elif choice == 'q' or choice == 'Q':
        print('欢迎再次使用,再见!')
        time.sleep(1)
        Exit_flag = False
      else:
        print('Invaliable Options!')

3、用户数据文件:

{"003": {"Name": "wangwu", "Password": "qazwsx", "Credit": 16000, "Balance": 8000}, "004": {"Name": "zhaoliu", "Password": "edcrfv", "Credit": 18000, "Balance": 6000}, "002": {"Name": "lisi", "Password": "123456", "Credit": 14000, "Balance": 10000}, "009": {"Password": "qwerty", "Name": "hanmeimei", "Credit": 15000, "Balance": 15000}, "005": {"Name": "fengqi", "Password": "1234qwer", "Credit": 15000, "Balance": 10700}, "010": {"Name": "lilei", "Password": "qaswed", "Credit": 50000, "Balance": 50000}, "008": {"Name": "zhengshi", "Password": "123456", "Credit": 12345, "Balance": 12345}, "006": {"Name": "zhouba", "Password": "123456", "Credit": 20000, "Balance": 8300}, "001": {"Name": "zhangsan", "Password": "abcd1234", "Credit": 12000, "Balance": 12000}, "007": {"Name": "wujiu", "Password": "123456", "Credit": 20000, "Balance": 11243}}

4、相关日志内容:

登录日志:

2016-12-20  22:12:18 卡号 005 认证成功!
2016-12-20  22:14:20 卡号 005 认证成功!
2016-12-20  22:17:26 卡号 006 认证成功!
2016-12-20  22:18:06 卡号 005 认证成功!
2016-12-20  22:18:06 卡号 006 认证成功!
2016-12-20  22:21:10 卡号 005 认证失败!
2016-12-20  22:21:10 卡号 006 认证成功!
2016-12-20  22:23:17 卡号 006 认证成功!
2016-12-20  22:25:33 卡号 006 认证成功!
2016-12-20  22:26:14 卡号 006 认证成功!
2016-12-20  22:32:15 卡号 006 认证成功!
2016-12-20  22:44:57 卡号 005 认证成功!
2016-12-20  22:45:50 卡号 006 认证成功!
2016-12-20  22:47:10 卡号 006 认证成功!
2016-12-20  22:48:27 卡号 006 认证成功!
2016-12-20  22:49:30 卡号 006 认证成功!
2016-12-20  22:52:13 卡号 006 认证成功!
2016-12-20  22:53:44 卡号 006 认证成功!

交易日志:

2016-12-20  21:25:35 卡号 006 发起 repayment 业务,金额为: 100
2016-12-20  21:27:01 卡号 005 发起 repayment 业务,金额为: 100
2016-12-20  22:14:20 卡号 005 发起 repayment 业务,金额为: 100
2016-12-20  22:17:26 卡号 006 发起 transfer 业务,金额为: 300

以上所述是小编给大家介绍的使用Python3 编写简单信用卡管理程序,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!

Python 相关文章推荐
Python多线程编程(一):threading模块综述
Apr 05 Python
使用Python多线程爬虫爬取电影天堂资源
Sep 23 Python
利用pyinstaller或virtualenv将python程序打包详解
Mar 22 Python
Python实现的列表排序、反转操作示例
Mar 13 Python
在Pytorch中计算自己模型的FLOPs方式
Dec 30 Python
python实现将json多行数据传入到mysql中使用
Dec 31 Python
Spring Boot中使用IntelliJ IDEA插件EasyCode一键生成代码详细方法
Mar 20 Python
Python+Kepler.gl实现时间轮播地图过程解析
Jul 20 Python
Python基于pillow库实现生成图片水印
Sep 14 Python
Python 排序最长英文单词链(列表中前一个单词末字母是下一个单词的首字母)
Dec 14 Python
OpenCV-Python模板匹配人眼的实例
Jun 08 Python
Python爬虫中urllib3与urllib的区别是什么
Jul 21 Python
Python 遍历子文件和所有子文件夹的代码实例
Dec 21 #Python
详解python中的json的基本使用方法
Dec 21 #Python
win系统下为Python3.5安装flask-mongoengine 库
Dec 20 #Python
python查看微信好友是否删除自己
Dec 19 #Python
python用reduce和map把字符串转为数字的方法
Dec 19 #Python
python虚拟环境virualenv的安装与使用
Dec 18 #Python
更改Ubuntu默认python版本的两种方法python-&gt; Anaconda
Dec 18 #Python
You might like
使用PHP实现Mysql读写分离
2013/06/28 PHP
php实现递归的三种基本方式
2020/07/04 PHP
判断、添加和删除WordPress置顶文章的相关PHP函数小结
2015/12/10 PHP
javascript下arguments,caller,callee,call,apply示例及理解
2009/12/24 Javascript
javascript jscroll模拟html元素滚动条
2012/12/18 Javascript
js阻止默认事件与js阻止事件冒泡示例分享 js阻止冒泡事件
2014/01/27 Javascript
基于BootStrap Metronic开发框架经验小结【八】框架功能总体界面介绍
2016/05/12 Javascript
全面了解构造函数继承关键apply call
2016/07/26 Javascript
Angular学习笔记之angular的$filter服务浅析
2016/11/12 Javascript
JS兼容所有浏览器的DOMContentLoaded事件
2018/01/12 Javascript
使用淘宝镜像cnpm安装Vue.js的图文教程
2018/05/17 Javascript
Vue使用vue-recoure + http-proxy-middleware + vuex配合promise实现基本的跨域请求封装
2019/10/21 Javascript
D3.js 实现带伸缩时间轴拓扑图的示例代码
2020/01/20 Javascript
2分钟实现一个Vue实时直播系统的示例代码
2020/06/05 Javascript
MySQL中表的复制以及大型数据表的备份教程
2015/11/25 Python
3个用于数据科学的顶级Python库
2018/09/29 Python
对pandas的行列名更改与数据选择详解
2018/11/12 Python
详解Python学习之安装pandas
2019/04/16 Python
Python实现计算对象的内存大小示例
2019/07/10 Python
Python中IP地址处理IPy模块的方法
2019/08/16 Python
Django认证系统user对象实现过程解析
2020/03/02 Python
Python基于class()实现面向对象原理详解
2020/03/26 Python
pycharm下pyqt4安装及环境配置的教程
2020/04/24 Python
通过Python扫描代码关键字并进行预警的实现方法
2020/05/24 Python
关于python的缩进规则的知识点详解
2020/06/22 Python
Django视图类型总结
2021/02/17 Python
性能服装:HYLETE
2018/08/14 全球购物
校园文明标语
2014/06/13 职场文书
搞笑的爱情检讨书
2014/10/01 职场文书
2014年军人思想汇报范文
2014/10/12 职场文书
2014年教师业务工作总结
2014/12/19 职场文书
物业接待员岗位职责
2015/04/15 职场文书
2015暑假打工实践报告
2015/07/13 职场文书
乡镇干部学习心得体会
2016/01/23 职场文书
致毕业季:你如何做好自己的职业生涯规划书?
2019/07/01 职场文书
vue+iview实现手机号分段输入框
2022/03/25 Vue.js