Python實現atm機的功能

主要仍是參考網上內容,本身作了修改。雖然代碼有小bug,可是不影響學習和測試。
python


功能:app

1.額度:8000iphone

2.能夠提現,手續費5%ide

3.每個月最後一天出帳單,寫入文件學習

4.記錄每個月平常消費流水測試

5.提供還款接口spa


1.atm的腳本3d

[root@python 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.商品表
orm

[root@python atm]# cat shops.txt 
computer 6000
iphone 5000
mouse 250
keyboard 40
camera 8000
package 500
power 230


3.初始化帳號密碼
blog

[root@python 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
[root@python atm]# python create_userinfo.py 
{'xdg': ['888', '3000', '3000'], 'bob': ['666', '8000', '8000'], 'xtd': ['123456', '150000', '150000']}


4.顯示餘額變化

[root@python 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
[root@python atm]# python cat.py 
{'xdg': ['888', '3000', '3000'], 'bob': ['666', '8000', 1000], 'xtd': ['123456', '150000', '150000']}


5.使用方法

[root@python 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.流程圖

wKiom1jThB6hNNPLAATxxOm0TPE429.jpg

相關文章
相關標籤/搜索