设为首页 收藏本站
查看: 1026|回复: 0

[经验分享] Python实现atm机的功能

[复制链接]
累计签到:1 天
连续签到:1 天
发表于 2017-3-24 11:21:26 | 显示全部楼层 |阅读模式
主要还是参考网上内容,自己做了修改。虽然代码有小bug,但是不影响学习和测试。


功能:
1.额度:8000
2.可以提现,手续费5%
3.每月最后一天出账单,写入文件
4.记录每月日常消费流水
5.提供还款接口

1.atm的脚本
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
[iyunv@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.商品表

1
2
3
4
5
6
7
8
[iyunv@python atm]# cat shops.txt
computer 6000
iphone 5000
mouse 250
keyboard 40
camera 8000
package 500
power 230




3.初始化账号密码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
[iyunv@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



1
2
[iyunv@python atm]# python create_userinfo.py
{'xdg': ['888', '3000', '3000'], 'bob': ['666', '8000', '8000'], 'xtd': ['123456', '150000', '150000']}




4.显示余额变化
1
2
3
4
5
6
7
8
9
10
11
12
13
[iyunv@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



1
2
[iyunv@python atm]# python cat.py
{'xdg': ['888', '3000', '3000'], 'bob': ['666', '8000', 1000], 'xtd': ['123456', '150000', '150000']}




5.使用方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
[iyunv@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.流程图
iyunv.com-2017-3-2415.jpg


运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-354582-1-1.html 上篇帖子: centos7 Python安装及yum问题解决 下篇帖子: Redis 持久化策略 (RDB、AOF) atm机
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表