热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

开发笔记:Python实现atm机的功能

篇首语:本文由编程笔记#小编为大家整理,主要介绍了Python实现atm机的功能相关的知识,希望对你有一定的参考价值。主要还是参考网上内容,自己做了修改。虽然代码有小bu

篇首语:本文由编程笔记#小编为大家整理,主要介绍了Python实现atm机的功能相关的知识,希望对你有一定的参考价值。


主要还是参考网上内容,自己做了修改。虽然代码有小bug,但是不影响学习和测试。


功能:

额度:8000

可以提现,手续费5%

每月最后一天出账单,写入文件

记录每月日常消费流水

提供还款接口


1.atm的脚本

[[email protected] atm]# cat atm.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
‘‘‘
Date:2017-03-23
Author:Bob
‘‘‘
import os
import time
import pickle
import readline #解决退格键和上下键引起的乱码,需要安装readline和readline-devel包
#定义账单,商品和购物车
Bill = {}
products = {}
shoplist = []
#define Bill function, used to record billing details(account/time/describe/money).
def Bill(Account,Time,Description,RMB):
    Bill = {"Account":Account,"Time":Time,"Description":Description,"RMB":RMB}
    #用pickle模块把账单信息存入到bill文件中去
    pickle.dump(Bill,open("bill","a"))
#购物功能
def shop():
    print ‘\033[;32mWelcome to shopping!\n\033[0m‘
    with open(‘shops.txt‘) as f:
        for line in f.readlines():
            print ‘{}‘.format(line.strip())
    while 1:
        with open(‘shops.txt‘) as f:
            for line in f.readlines():
                line = line.strip()
                commodity = line.split()[0]
                price = line.split()[1]
                products[commodity] = price
            choice = raw_input("\n\033[;36mPlease enter what you want to buy,if you want back,you can enter\033[0m \033[;31mback\033[0m:").strip()
            if len(choice) == 0:
                continue
            elif choice == ‘back‘:
                list()
            #如果有这个商品,就判断商品价格,如果商品价格大于余额,就提示余额不足
            if products.has_key(choice):
                #从userinfo文件中读取并反序列化
                remaining = pickle.load(open(‘userinfo‘,‘rb‘))
                if int(products[choice]) > remaining[accountAuth][2]:
                    print ‘In your card remaining sum already insufficiency, please prompt sufficient value!‘
                else:
                    while 1:
                        #把购买的商品追加到购物车
                        shoplist.append(choice)
                        #计算余额,余额就是总金额减去购买的商品价格
                        new_remaining = int(remaining[accountAuth][2]) - int(products[choice])
                        userInfo[accountAuth][2] = int(new_remaining)
                        #把余额信息序列化并存到userinfo文件中
                        pickle.dump(userInfo,open("userinfo","wb"))
                        #把购买的记录和账单写到Bill文件中
                        Bill(accountAuth,time.strftime("%Y-%m-%d %H:%M:%S"),choice,"-%d" % int(products[choice]))
                        #打印消费的金额和剩余金额
                        print "\033[;32mConsumption is %r Money is %r\033[0m" % (products[choice],new_remaining)
                        #打印购物车的商品
                        print "\033[;33mThe shopping list %s \033[0m" % shoplist
                        break
            else:
                print ‘You choose {} is not in the shoplist!‘.format(choice)
                shop()
#查询余额功能
def query_money():
    userInfo = pickle.load(open(‘userinfo‘,‘rb‘))
    totalmoney = userInfo[accountAuth][1]
    remaining = userInfo[accountAuth][2]
    print ‘Your total money is {}, remaining money is \033[1;31m{}\033[0m!‘.format(totalmoney, remaining)
#存钱功能
def save_money():
    while 1:
        save_desc = raw_input("Please describe save money the details:").strip()
        if len(save_desc) == 0:
            continue
        try:
            save_money = int(raw_input("Please save the money:"))
        except ValueError:
            print "\033[;31mYou entered must be number.\033[0m"
            save_money()
        if save_money % 100 != 0:
            print ‘You must enter an integer of 100!‘
            continue
        userInfo = pickle.load(open(‘userinfo‘, ‘rb‘))
        remaining = int(userInfo[accountAuth][2]) + save_money
        userInfo[accountAuth][2] = remaining
        pickle.dump(userInfo, open(‘userinfo‘, ‘wb‘))
        print ‘Your total money is %s, your remaining is \033[;31m%s\033[0m!‘ %(userInfo[accountAuth][1], userInfo[accountAuth][2])
        Bill(accountAuth,time.strftime("%Y-%m-%d %H:%M:%S"),save_desc,"+%d" % float(save_money))
        next = raw_input("1.continue \n2.return \n3.exit \nPlease select: ").strip()
        if next == ‘1‘:
            continue
        elif next == ‘2‘:
            list()
        elif next == ‘3‘:
            exit()
        else:
            print ‘Please enter the correct content!‘
#取钱功能
def draw_money():
    while 1:
        draw_desc = raw_input("Please describe draw money the details:").strip()
        if len(draw_desc) == 0:
            continue
        try:
            draw_money = int(raw_input("Please draw the money:"))
        except ValueError:
            print "\033[;31mYou entered must be number.\033[0m"
            draw_money()
    
        if draw_money % 100 != 0:
            print ‘You must enter an integer of 100!‘
            continue
     
        userInfo = pickle.load(open(‘userinfo‘, ‘rb‘))
        #There are bugs here!
        if draw_money > int(userInfo[accountAuth][2]):
            print ‘\033[;31mYour remaining is insufficient!\033[0m‘
            list()
        userInfo = pickle.load(open(‘userinfo‘, ‘rb‘))
        remaining = int(userInfo[accountAuth][2]) - draw_money - draw_money * 0.05
        userInfo[accountAuth][2] = remaining
        pickle.dump(userInfo, open(‘userinfo‘, ‘wb‘))
        print ‘Your total money is %s, your remaining is \033[;31m%s\033[0m!‘ %(userInfo[accountAuth][1], userInfo[accountAuth][2])
        Bill(accountAuth,time.strftime("%Y-%m-%d %H:%M:%S"),draw_desc,"+%d" % float(draw_money))
        next = raw_input("1.continue \n2.return \n3.exit \nPlease select: ").strip()
        if next == ‘1‘:
            continue
        elif next == ‘2‘:
            list()
        elif next == ‘3‘:
            exit()
        else:
            print ‘Please enter the correct content!‘
#转账功能,和上面的逻辑基本一样
def transfer_money():
    while 1:
        userInfo = pickle.load(open(‘userinfo‘, ‘rb‘))
        transfer_desc = raw_input("Please describe transfer money: ").strip()
        if len(transfer_desc) == 0:
            continue
        d_account = raw_input("Please input transfer account: ").strip()
        if len(d_account) == 0:
            continue
        if userInfo.has_key(d_account) is False:
            print "\033[;31mThis account does not exist\033[0m"
            transfer_money()
        d_money = int(raw_input("Please input transfer amount money: "))
        if d_money % 100 != 0:
            print "\033[;31mDeposit amount must be 100 integer times\033[0m"
            continue
        if d_money > int(userInfo[accountAuth][2]):
            print "\033[;31mYour balance is insufficient\033[0m"
            continue
        userInfo[accountAuth][2] = int(userInfo[accountAuth][2]) - d_money - d_money * 0.10
        userInfo[d_account][2] = int(userInfo[d_account][2]) + d_money
        pickle.dump(userInfo,open(‘userinfo‘, ‘wb‘))
        print "\033[;32mYour credit is %r,Your balance is %r\033[0m" % (userInfo[accountAuth][1],userInfo[accountAuth][2])
        Bill(accountAuth,time.strftime("%Y-%m-%d %H:%M:%S"),transfer_desc,"-%d" % (userInfo[accountAuth][2] - d_money - d_money * 0.10))
        next = raw_input("1.continue \n2.return \n3.exit \nPlease select: ").strip()
        if next == ‘1‘:
            continue
        elif next == ‘2‘:
            list()
        elif next == ‘3‘:
            exit()
        else:
            print ‘Please enter the correct content!‘
#账单功能
def query_bill():
    Income = []
    Spending = []
    num = 0
    print "Account\t\tTime\t\tDescription\t\t  RMB"
    with open(‘bill‘, ‘rb‘) as f:
        while True:
            try:
                line = pickle.load(f)
                if line["Account"] == accountAuth:
                    if ‘+‘ in line["RMB"]:
                        print "\033[;33m%r\t%r\t%r\t\t\t%r\033[0m" % (line["Account"],line["Time"],line["Description"],line["RMB"])
                        income = line["RMB"].strip("+")
                        Income.append(income)
                    else:
                        print "%r\t%r\t%r\t\t\t%r" % (line["Account"],line["Time"],line["Description"],line["RMB"])
                        spending = line["RMB"].strip("-")
                        Spending.append(spending)
            except:
                break
    for i in Income:
        num = num + int(i)
    income = num
    print "Income is %r" % num
    for i in Spending:
        num = num + int(i)
    spending = num
    print "Spending is %r" % num
    print "Total is %r" % (int(income) + int(spending))
#修改密码功能
def modify_passwd():
    userInfo = pickle.load(open(‘userinfo‘, ‘rb‘)) 
    old_passwd = raw_input("Please enter old password:").strip()
    while 1:
        if old_passwd == userInfo[accountAuth][0]:
            new_passwd = raw_input("Please enter new password:").strip()
            if len(new_passwd) < 6:
                print ‘Your password is too simple!‘
                continue
            confirm_new_password = raw_input("Please confirm new password again:").strip()
            if new_passwd != confirm_new_password:
                print ‘Two passwords do not match!‘
            else:
                userInfo[accountAuth][0] = confirm_new_password
                pickle.dump(userInfo, open(‘userinfo‘, ‘wb‘))
                print ‘\033[;32mYour password is changed successful!\033[0m‘
                exit()
        else:
            print ‘Your password is error!‘
            modify_passwd()
#ATM机所有功能
def list():
    print ‘‘‘\033[;32m
###################################################
#            welcome to ATM!                      #
#                                                 #
#    1.shop               2.query money           #
#    3.save money         4.draw money            #
#    5.transfer money     6.query bill            #
#    7.modify password    8.exit                  #
#                                                 #
###################################################
\033[0m‘‘‘
    while 1:
        choice = raw_input("Please choose according to your needs:").strip()
        if len(choice) == 0:
            continue
        elif choice == ‘1‘:
            shop()
        elif choice == ‘2‘:
            query_money()
        elif choice == ‘3‘:
            save_money()
        elif choice == ‘4‘:
            draw_money()
        elif choice == ‘5‘:
            transfer_money()
        elif choice == ‘6‘:
            query_bill()
        elif choice == ‘7‘:
            modify_passwd()
        else:
            print "\n\033[;35mYou have been exit the system!\033[0m"
            exit()
#用户登录功能
userInfo = pickle.load(open(‘userinfo‘, ‘rb‘))
while 1:
    accountAuth = raw_input("Please input user account:").strip()
    if len(accountAuth) == 0:
        continue
    if userInfo.has_key(accountAuth):
        if ‘lock‘ in userInfo[accountAuth]:
            print ‘%s has been locked!‘ % accountAuth
            exit()
        for num in range(3,0,-1):
            passwdAuth = raw_input("Please input user password:").strip()
            if len(passwdAuth) == 0:
                continue
            if passwdAuth == userInfo[accountAuth][0]:
                list()
            else:
                print "Wrong password, Can try again \033[;31m%r\033[0m itmes" % num
                continue
        else:
                lockaccount = userInfo[accountAuth]
                lockaccount.append(‘lock‘)
                pickle.dump(userInfo,open(‘userinfo‘, ‘wb‘))
                print "\033[;31mAccount freeze within 24 hours\033[0m"
                exit()
    else:
        print "\033[;31mWrong account %r,retype\033[0m" % accountAuth


2.商品表

[[email&#160;protected] atm]# cat shops.txt 
computer 6000
iphone 5000
mouse 250
keyboard 40
camera 8000
package 500
power 230


3.初始化账号密码

[[email&#160;protected] atm]# cat create_userinfo.py 
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pickle
userInfo = {‘xtd‘:[‘123456‘,‘150000‘,‘150000‘],
            ‘bob‘:[‘666‘,‘8000‘,‘8000‘],
            ‘xdg‘:[‘888‘,‘3000‘,‘3000‘]
            }
pickle.dump(userInfo,open(‘userinfo‘, ‘w‘))
userinfo = open(‘userinfo‘, ‘r‘)
while True:
    try:
        line = pickle.load(userinfo)
        print line
    except:
        break

[[email&#160;protected] atm]# python create_userinfo.py 
{‘xdg‘: [‘888‘, ‘3000‘, ‘3000‘], ‘bob‘: [‘666‘, ‘8000‘, ‘8000‘], ‘xtd‘: [‘123456‘, ‘150000‘, ‘150000‘]}


4.显示余额变化

[[email&#160;protected] atm]# cat cat.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pickle
userinfo = open(‘userinfo‘, ‘r‘)
while True:
    try:
        line = pickle.load(userinfo)
        print line
    except:
        break

[[email&#160;protected] atm]# python cat.py 
{‘xdg‘: [‘888‘, ‘3000‘, ‘3000‘], ‘bob‘: [‘666‘, ‘8000‘, 1000], ‘xtd‘: [‘123456‘, ‘150000‘, ‘150000‘]}


5.使用方法

[[email&#160;protected] atm]# python atm.py 
Please input user account:bob
Please input user password:666
###################################################
#            welcome to ATM!                      #
#                                                 #
#    1.shop               2.query money           #
#    3.save money         4.draw money            #
#    5.transfer money     6.query bill            #
#    7.modify password    8.exit                  #
#                                                 #
###################################################
Please choose according to your needs:2
Your total money is 8000, remaining money is 1000!
Please choose according to your needs:


6.流程图

技术分享

本文出自 “卡卡西” 博客,请务必保留此出处http://whnba.blog.51cto.com/1215711/1909696


推荐阅读
  • 本文讨论了在openwrt-17.01版本中,mt7628设备上初始化启动时eth0的mac地址总是随机生成的问题。每次随机生成的eth0的mac地址都会写到/sys/class/net/eth0/address目录下,而openwrt-17.01原版的SDK会根据随机生成的eth0的mac地址再生成eth0.1、eth0.2等,生成后的mac地址会保存在/etc/config/network下。 ... [详细]
  • 本文由编程笔记#小编为大家整理,主要介绍了logistic回归(线性和非线性)相关的知识,包括线性logistic回归的代码和数据集的分布情况。希望对你有一定的参考价值。 ... [详细]
  • 生成式对抗网络模型综述摘要生成式对抗网络模型(GAN)是基于深度学习的一种强大的生成模型,可以应用于计算机视觉、自然语言处理、半监督学习等重要领域。生成式对抗网络 ... [详细]
  • VScode格式化文档换行或不换行的设置方法
    本文介绍了在VScode中设置格式化文档换行或不换行的方法,包括使用插件和修改settings.json文件的内容。详细步骤为:找到settings.json文件,将其中的代码替换为指定的代码。 ... [详细]
  • 目录实现效果:实现环境实现方法一:基本思路主要代码JavaScript代码总结方法二主要代码总结方法三基本思路主要代码JavaScriptHTML总结实 ... [详细]
  • 本文讨论了在Windows 8上安装gvim中插件时出现的错误加载问题。作者将EasyMotion插件放在了正确的位置,但加载时却出现了错误。作者提供了下载链接和之前放置插件的位置,并列出了出现的错误信息。 ... [详细]
  • CSS3选择器的使用方法详解,提高Web开发效率和精准度
    本文详细介绍了CSS3新增的选择器方法,包括属性选择器的使用。通过CSS3选择器,可以提高Web开发的效率和精准度,使得查找元素更加方便和快捷。同时,本文还对属性选择器的各种用法进行了详细解释,并给出了相应的代码示例。通过学习本文,读者可以更好地掌握CSS3选择器的使用方法,提升自己的Web开发能力。 ... [详细]
  • 如何使用Java获取服务器硬件信息和磁盘负载率
    本文介绍了使用Java编程语言获取服务器硬件信息和磁盘负载率的方法。首先在远程服务器上搭建一个支持服务端语言的HTTP服务,并获取服务器的磁盘信息,并将结果输出。然后在本地使用JS编写一个AJAX脚本,远程请求服务端的程序,得到结果并展示给用户。其中还介绍了如何提取硬盘序列号的方法。 ... [详细]
  • 本文介绍了九度OnlineJudge中的1002题目“Grading”的解决方法。该题目要求设计一个公平的评分过程,将每个考题分配给3个独立的专家,如果他们的评分不一致,则需要请一位裁判做出最终决定。文章详细描述了评分规则,并给出了解决该问题的程序。 ... [详细]
  • javascript  – 概述在Firefox上无法正常工作
    我试图提出一些自定义大纲,以达到一些Web可访问性建议.但我不能用Firefox制作.这就是它在Chrome上的外观:而那个图标实际上是一个锚点.在Firefox上,它只概述了整个 ... [详细]
  • 不同优化算法的比较分析及实验验证
    本文介绍了神经网络优化中常用的优化方法,包括学习率调整和梯度估计修正,并通过实验验证了不同优化算法的效果。实验结果表明,Adam算法在综合考虑学习率调整和梯度估计修正方面表现较好。该研究对于优化神经网络的训练过程具有指导意义。 ... [详细]
  • 本文介绍了一个在线急等问题解决方法,即如何统计数据库中某个字段下的所有数据,并将结果显示在文本框里。作者提到了自己是一个菜鸟,希望能够得到帮助。作者使用的是ACCESS数据库,并且给出了一个例子,希望得到的结果是560。作者还提到自己已经尝试了使用"select sum(字段2) from 表名"的语句,得到的结果是650,但不知道如何得到560。希望能够得到解决方案。 ... [详细]
  • CF:3D City Model(小思维)问题解析和代码实现
    本文通过解析CF:3D City Model问题,介绍了问题的背景和要求,并给出了相应的代码实现。该问题涉及到在一个矩形的网格上建造城市的情景,每个网格单元可以作为建筑的基础,建筑由多个立方体叠加而成。文章详细讲解了问题的解决思路,并给出了相应的代码实现供读者参考。 ... [详细]
  • 本文详细介绍了MySQL表分区的创建、增加和删除方法,包括查看分区数据量和全库数据量的方法。欢迎大家阅读并给予点评。 ... [详细]
  • MyBatis多表查询与动态SQL使用
    本文介绍了MyBatis多表查询与动态SQL的使用方法,包括一对一查询和一对多查询。同时还介绍了动态SQL的使用,包括if标签、trim标签、where标签、set标签和foreach标签的用法。文章还提供了相关的配置信息和示例代码。 ... [详细]
author-avatar
彤彤柯安_839
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有