python模拟银行ATM程序设计
- 格式:doc
- 大小:182.00 KB
- 文档页数:16
ATM自动取款机程序设计
ATM自动取款机程序设计
1. 简介
ATM(自动取款机)是一种自动化设备,用户可以在不需要银行工作人员的情况下,自行进行各种银行业务操作,包括取款、查询余额、转账等。
为了实现这样的功能,需要设计一个ATM自动取款机程序。
2. 设计思路
ATM自动取款机程序的设计需要考虑以下几个方面:
用户身份认证:用户需要通过输入正确的账号和密码进行身份认证,确保只有合法用户可以进行操作。
功能选项:用户登录成功后,系统需要提供各种功能选项供用户选择,如取款、查询余额、转账等。
金额验证:在进行取款、转账等操作时,需要验证用户输入的金额是否合法,包括用户的账户余额是否足够等。
交易记录:系统需要记录每一笔交易的相关信息,包括交易时间、金额、余额等。
安全性:程序需要确保用户的账号和密码等敏感信息不会被泄露,并且在网络传输时进行加密保护。
3. 基本功能实现
3.1 用户身份认证
用户需要输入正确的账号和密码进行身份认证,可以使用数据库存储用户账号和密码的方式来验证用户输入的信息是否正确。
3.2 功能选项
用户登录成功后,系统需要提供各种功能选项供用户选择,可以使用菜单的方式展示选项,用户根据菜单选择数字或字母对应的功能。
例如,用户输入\。
python模拟银行系统实验报告Python模拟银行系统实验报告一、实验目的本实验旨在通过使用Python语言编写一个简单的银行系统程序,掌握Python语言的基本语法和面向对象编程思想,加深对Python编程的理解和应用。
二、实验环境本实验在Windows 10操作系统下进行,使用Python 3.7.4版本进行编程。
三、实验步骤1. 创建一个BankAccount类,定义账户属性和方法。
```pythonclass BankAccount:def __init__(self, name, balance): = nameself.balance = balancedef deposit(self, amount):self.balance += amountdef withdraw(self, amount):if amount > self.balance:print("Insufficient balance!")else:self.balance -= amountdef get_balance(self):return self.balance```2. 创建一个BankSystem类,定义系统属性和方法。
```pythonclass BankSystem:def __init__(self):self.accounts = []def add_account(self, account):self.accounts.append(account)def find_account(self, name):for account in self.accounts:if == name:return accountreturn Nonedef transfer_money(self, sender_name, receiver_name, amount):sender_account = self.find_account(sender_name)receiver_account = self.find_account(receiver_name)if sender_account is None or receiver_account is None: print("Account not found!")returnif sender_account.get_balance() < amount:print("Insufficient balance!")returnsender_account.withdraw(amount)receiver_account.deposit(amount)```3. 创建一个BankUI类,定义用户界面和交互方法。
ATM模拟程序说明
系统主程序为根目录下的:day5_credit_card.py
1.系统功能模块
Day5_ATM模拟程序是在python3.0环境下开发,主要功能模块如下图:
2.系统目录结构:
程序采用分层的方式编写,包括数据库访问层、数据库层(数据文件)、业务逻辑层(module层),业务处理层(主程序)、
主要分类如下图:
3.应用知识点:
a)字典、列表、元组的操作
b)文件的读写操作
c)函数的应用
d)类的使用
e)装饰器、反射
f)系统模块、自定义模块的操作
4 各模块功能图概要如下:
4.1 购物商城模块
4.2 用户登录模块(用户中心)
4.3 信用卡中心模块
4.4 后台管理模块
5.1 主菜单
5.2 进入商城
5.3 加入购物车
5.4 查看购物车
5.5 支付时装饰器验证登录
5.6 查看流水
5.7 查询购物记录
5.8 还款。
pythonatm机程序代码Python ATM机程序代码随着科技的不断发展,ATM机已经成为了人们日常生活中不可或缺的一部分。
ATM机的出现,不仅方便了人们的生活,也提高了人们的生活质量。
而在ATM机的背后,是一系列复杂的程序代码在运行。
本文将介绍一种基于Python语言的ATM机程序代码。
一、ATM机的基本功能ATM机的基本功能包括:查询余额、取款、存款、转账、修改密码等。
在Python ATM机程序代码中,这些功能都被封装成了函数,方便调用。
1.查询余额查询余额是ATM机最基本的功能之一。
在Python ATM机程序代码中,查询余额的函数如下:```def query_balance():print("您的余额为:", balance)```其中,balance为全局变量,表示用户的余额。
2.取款取款是ATM机的另一个重要功能。
在Python ATM机程序代码中,取款的函数如下:```def withdraw():global balanceamount = int(input("请输入取款金额:"))if amount > balance:print("余额不足!")else:balance -= amountprint("取款成功!")print("您的余额为:", balance)```其中,amount为用户输入的取款金额,如果余额不足,则提示“余额不足!”;否则,从余额中扣除取款金额,并提示“取款成功!”。
3.存款存款是ATM机的另一个重要功能。
在Python ATM机程序代码中,存款的函数如下:```def deposit():global balanceamount = int(input("请输入存款金额:"))balance += amountprint("存款成功!")print("您的余额为:", balance)```其中,amount为用户输入的存款金额,将存款金额加入余额中,并提示“存款成功!”。
程序设计基础(一)综合作业银行ATM机工作流程模拟编程班级学号姓名[综合作业目的]1、通过编程及上机调试,掌握函数、文件、结构及链表的综合应用;2、掌握查找、排序等基本算法;3、掌握模块化程序设计的方法。
[综合作业内容]编程,模拟一个ATM(Automatic Teller Machine,自动取款机)的工作流程。
依据帐户信息:姓名、帐号、密码、余额,完成ATM机功能:登录、显示余额、取款、修改密码。
具体要求:1、合理规划数据结构,以保存储户信息;2、使用链表结构记录有关数据,使用链表完成相关操作;3、使用文件记载储户信息,程序启动时加载储户信息,程序退出时保存储户信息;4、程序工作流程:●显示登录界面:帐号:密码:接受用户输入。
●若为非法用户,提示出错,并重新登录,3次出错后退出;●若为合法用户,则显示操作菜单,提供下述服务:①显示基本信息②修改密码③查询余额④存款⑤取款(每次取款额度为¥5000元)⑥退出5、* 用户一次登录后的取款总数超过¥50000者,则程序自动产生一个明细记录,记载该用户的登录时间、地点(登录时间、地点假设已知,并用字符串表示)。
考虑此种情况较少出现,为节省存储空间,不宜在描述储户信息的数据结构中直接分配字符数组(建议在其数据结构中添加一个指向字符串数组的指针,…);6、提交设计文档及源代码清单。
[综合作业要求]1、独立、按时完成综合作业;2、进行需求分析,完成相关数据结构的规划与设计;3、实现菜单所列功能。
具体要求:每个功能为一个独立的函数;所有的输入之前都要有提示。
4、在程序的调试中,应用所学的计算机知识,完成大批数据的输入。
并列出完整、严格的测试结果(包括输入和输出);5、提交完整的C代码及设计文档(包括设计方案、具体功能及实现、特点小结等)。
1。
PythonATM功能实现代码实例编写ATM程序实现下述功能,数据来源于⽂件db.txt1、充值功能:⽤户输⼊充值钱数,db.txt中该账号钱数完成修改2、转账功能:⽤户A向⽤户B转账1000元,db.txt中完成⽤户A账号减钱,⽤户B账号加钱3、提现功能:⽤户输⼊提现⾦额,db.txt中该账号钱数减少4、查询余额功能:输⼊账号查询余额登录功能⽤户登录成功后,内存中记录下该状态,上述功能以当前登录状态为准,必须先登录才能操作代码如下import osuser_staus = {'username': None}def ad_credit(username, amount):"""充值功能:param username::param amount::return:"""if user_staus['username'] is None:login()with open('db.txt', 'rt', encoding='utf-8')as f1, \open('db.txt.swap', 'wt', encoding='utf-8')as f2:while True:cont = f1.readline()if len(cont) == 0:breakname, remain = cont.strip().split(':')if username in name:remain = int(remain) + int(amount)f2.write('{}:{}\n'.format(name, remain))print('充值成功,{}的余额为{}'.format(username, remain))else:f2.write(cont)os.remove('db.txt')os.rename('db.txt.swap', 'db.txt')def transfer(user_out, user_in, amount):'''3转账功能:param user_out::param user_in::param amount::return:'''if user_staus['username'] is None:login()with open('db.txt', 'rt', encoding='utf-8')as f1, \open('db.txt.swap', 'wt', encoding='utf-8')as f2:userinfo = {}for line in f1:name, remind = line.strip().split(':')userinfo[name] = int(remind)if user_out not in userinfo:print('⽤户不存在')returnif user_in not in userinfo:print('收款⽅不存在')returnif user_out in userinfo and user_in in userinfo:if userinfo[user_out] >= int(amount):userinfo[user_out] -= int(amount)userinfo[user_in] += int(amount)print('转账成功,已成功从{}向{}汇款{}'.format(user_out, user_in, amount)) elif userinfo[user_out] < amount:print('余额不⾜')returnfor name, remind in userinfo.items():f2.write('{}:{}\n'.format(name, remind))os.remove('db.txt')os.rename('db.txt.swap', 'db.txt')def cashon(username, amount):'''提现功能:param username::param amount::return:'''if user_staus['username'] is None:login()with open('db.txt', 'rt', encoding='utf-8')as f1, \open('db.txt.swap', 'wt', encoding='utf-8')as f2:userinfo = {}for line in f1:name, remind = line.strip().split(':')userinfo[name] = int(remind)if username not in userinfo:print('⽤户不存在')returnif username in userinfo and userinfo[username] >= int(amount):userinfo[username] -= int(amount)print('已从余额中取出{},现余额为{}'.format(amount, userinfo[username])) elif userinfo[username] < amount:print('余额不⾜,提现失败')returnfor name, remind in userinfo.items():f2.write('{}:{}\n'.format(name, remind))os.remove('db.txt')os.rename('db.txt.swap', 'db.txt')def check(username):'''余额查询功能:param username::return:'''if user_staus['username'] is None:login()with open('db.txt', 'rt', encoding='utf-8')as f:userinfo = {}for line in f:name, remind = line.strip().split(':')userinfo[name] = remindif username not in userinfo:print('⽤户不存在')returnif username in userinfo:print('当前余额为:{}'.format(userinfo[username]))def login():username = input('输⼊⽤户名')userpassword = input('输⼊密码')with open('login.txt', 'rt', encoding='utf-8')as login_f:login = {}for line in login_f:name, psd = line.strip().split(':')login[name] = psdif username in login:if login[username] == userpassword:print('登陆成功')user_staus['username'] = usernamebreakelif username not in login:print('⽤户名不存在')returndef logout():user_staus['username'] = Noneprint('已成功登出')returnlogin()tag = Truewhile tag:cmd = input('''请输⼊你想使⽤的功能序号1:充值2:转账3:提现4:查询余额0:登出''')if cmd == '1':username = input('输⼊⽤户名:')amount = input('输⼊充值⾦额:')ad_credit(username, amount)elif cmd == '2':user_out = input('请输⼊转账⽅:')user_in = input('请输⼊接收⽅:')amount = input('输⼊转账⾦额:')transfer(user_out, user_in, amount)elif cmd == '3':username = input('输⼊⽤户名:')amount = input('输⼊提现⾦额')cashon(username, amount)elif cmd == '4':username = input('输⼊⽤户名:')check(username)elif cmd == '0':logout()tag = Falseelse:print('请正确输⼊序号')以下是模拟结果'''/Users/chenfeng/PycharmProjects/ATM/venv/bin/python /Users/chenfeng/PycharmProjects/ATM/main.py 输⼊⽤户名xilou输⼊密码666登陆成功请输⼊你想使⽤的功能序号1:充值2:转账3:提现4:查询余额0:登出1输⼊⽤户名:xilou输⼊充值⾦额:200充值成功,xilou的余额为700请输⼊你想使⽤的功能序号1:充值2:转账3:提现4:查询余额0:登出2请输⼊转账⽅:xilou请输⼊接收⽅:heiren输⼊转账⾦额:200转账成功,已成功从xilou向heiren汇款200请输⼊你想使⽤的功能序号1:充值2:转账3:提现4:查询余额0:登出3输⼊⽤户名:xilou输⼊提现⾦额100已从余额中取出100,现余额为400请输⼊你想使⽤的功能序号1:充值2:转账3:提现4:查询余额0:登出4输⼊⽤户名:xilou当前余额为:400请输⼊你想使⽤的功能序号1:充值2:转账3:提现4:查询余额0:登出已成功登出Process finished with exit code 0'''以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
2.3,ATM自动取款机模拟程序2.3.1总体设计:流程图2.3.2详细设计:登陆系统主界面开户业务模板:void openAccount()。
主要功能在于新开账户(也可为下面转账系统服务等做铺。
)且储存信息。
经提升,密码已可以包含字符。
用户可根据提示,一步步完成操作。
主要代码:void openAccount()//开户函数{system("cls");cout<<"\t************************************\n"<<endl;cout<<"\t* 开户业务*\n"<<endl;cout<<"\t************************************\n"<<endl;cout<<"\t欢迎使用开户业务,请按照提示操作!\n"<<endl;cout<<"\n"<<endl;cout<<"\t\t请输入你的用户名:";cin>>user[st].n;cout<<"\t\t请输入你的卡号:";int k1;//k1表示新用户输入的卡号cin>>k1;int a=-1;//用来做标示for(int i=0;i<st;i++){if(user[i].k==k1){a++;}}if(a==-1){user[st].k=k1;//将k1的数值赋值给user[st].k保存起来cout<<"\t\t请输入你的性别:";char xb[5];cin>>xb;strcpy(user[st].sex,xb);cout<<"\t\t请输入密码:";char m2[20];cin>>m2;strcpy(user[st].mm,m2);//保存用户输入可以包含字符的密码cout<<"\t\t请输入你的开户金额:";float km;cin>>km;//km表示用户的开户金额user[st].je=km;//je将开户时的金额赋值给user[st].je保存if(km<10){cout<<"\t\t你输入的金额小于10元或输入有误!\n";}else{cout<<"\t\t恭喜你,开户成功!\n"<<endl;cout<<"\t\t你的用户名为:"<<user[st].n<<endl;cout<<"\t\t你的卡号为:"<<user[st].k<<endl;cout<<"\t\t你的当前余额为:"<<user[st].je<<endl;cout<<"\n"<<endl;st++;//用于统计新开用户后现有的用户数}}else{cout<<"\t\t你输入的卡号已存在!请核实!\n"<<endl;}}缴费业务模板:主要提供给用户缴费服务关键代码:cout<<"\t\t请输入你要缴费的金额:";float j1;//j1表示用户存款时存取的金额cin>>j1;user[a].je=user[a].je+j1;cout<<"\t\t恭喜你,缴费成功!当前余额为:"<<user[a].je<<endl; 取款业务模板:主要功能用于用户的提款cout<<"\t\t请输入你要取出的金额:";float j1;//j1表示用户粗款时存取的金额cin>>j1;if(j1>user[a].je){cout<<"\t\t\a\a\a你输入账户余额仅为:"<<user[a].je;}else{user[a].je=user[a].je-j1;cout<<"\t\t取款成功!当前余额为:"<<user[a].je<<endl;查询余额业务模板:主要提供用户余额的查询服务cout<<"\t\t当前余额为:"<<user[a].je<<endl;查询个人信息业务模板:主要提供用户个人信息的模板cout<<"\t\t\t用户名:"<<user[a].n<<endl;cout<<"\t\t\t性别:"<<user[a].sex<<endl;cout<<"\t\t\t卡号:"<<user[a].k<<endl;cout<<"\t\t\t当前余额:"<<user[a].je<<endl;转账业务模板:提供用户转取个人金额服务的模板关键代码:cout<<"\t\t请输入你要转入的用户的账号:";int m2,b=-1;//b用来标示cin>>m2;for(int i=0;i<st;i++){if(user[i].k==m2){b=i;}} Array if(b!=-1){cout<<"\t\t你要转入用户的信息:\n"<<endl;cout<<"\t\t姓名:"<<user[b].n<<endl;cout<<"\t\t性别:"<<user[b].sex<<endl;cout<<"\t\t\a是否继续??继续请按任意键"<<endl;char n;n=getch();cout<<"\n\t\t请输入你要转取的金额:";float j1;//j1表示用户存款时存取的金额cin>>j1;if(j1>user[a].je){cout<<"\t\t你的账户余额不足,不能进行转账!"<<endl;}else{user[a].je=user[a].je-j1;cout<<"\t\t\a转账成功!当前你账户余额为:"<<user[a].je<<endl;}对卡服务模板:主要提供用户操作完毕后退卡的服务主要代码:cout<<"\t\t按Enter键返回主菜单!\n"<<endl;getchar();system("cls");代码:4.3 ATM自动取款机模拟程序(面向对象)#include<iostream.h>#include<stdio.h>#include<stdlib.h>class ATM{public:char name[10];//保存用户姓名long cardID;//保存卡号long psw;//密码ATM(){cardID=123123;psw=123;money=100;}void openAccount()//开户函数{system("cls");cout<<"\t************************************\n"<<endl;cout<<"\t* 开户业务*\n"<<endl;cout<<"\t************************************\n"<<endl;cout<<"\t欢迎使用开户业务,请按照提示操作!\n"<<endl;cout<<"\n"<<endl;cout<<"\t\t请输入您的姓名:"<<endl;cin>>name;cout<<"\t\t请输入您的卡号:"<<endl;cin>>cardID;cout<<"\t\t请输入您的密码:"<<endl;cin>>psw;cout<<"\t\t请输入您的预存金额:"<<endl;cin>>money;cout<<"\t\t恭喜您,开户成功!\n"<<endl;}void saveMoney()//缴费{system("cls");cout<<"\t************************************\n"<<endl;cout<<"\t* 存款业务*\n"<<endl;cout<<"\t************************************\n"<<endl;cout<<"\t欢迎使用存款业务,请按照提示操作!\n"<<endl;cout<<"\n"<<endl;long cid;long psw1;int money1;cout<<"\t\t请输入您的卡号:";cin>>cid;cout<<"\t\t请输入您的密码:";cin>>psw1;if(cid==cardID &&psw1==psw){cout<<"\t\t请输入您的存款金额:";cin>>money1;money=money+money1;cout<<"\t\t取款成功,卡上余额为:"<<money<<endl;}else{cout<<"\t\t您输入的卡号或密码有误!"<<endl;}}void takeMoney()//取款{system("cls");cout<<"\t************************************\n"<<endl;cout<<"\t* 取款业务*\n"<<endl;cout<<"\t************************************\n"<<endl;cout<<"\t欢迎使用取款业务,请按照提示操作!\n"<<endl;cout<<"\n"<<endl;long cid;long psw1;int money1;cout<<"\t\t请输入您的卡号:";cin>>cid;cout<<"\t\t请输入您的密码:";cin>>psw1;if(cid==cardID && psw1==psw){cout<<"\t\t请输入您取款的金额:";cin>>money1;money=money-money1;cout<<"\t\t取款成功,您卡上余额为:"<<money;}else{cout<<"\t\t温馨提示:您的卡号或密码错误,注意密码尝试三次后将被吞卡!\n"<<endl;}}void query()//查询余额{system("cls");cout<<"\t************************************\n"<<endl;cout<<"\t* 查询余额业务*\n"<<endl;cout<<"\t************************************\n"<<endl;cout<<"\t欢迎使用查询余额业务,请按照提示操作!\n"<<endl;cout<<"\n"<<endl;long cid;long psw1;cout<<"\t\t请输入您的卡号:";cin>>cid;cout<<"\t\t请输入您的密码:";cin>>psw1;if(cid==cardID && psw1==psw){cout<<"\t\t卡上余额为:"<<money<<endl;}else{cout<<"\t\t您的卡号或密码错误!\n";}}void transfer()//转账{system("cls");cout<<"\t************************************\n"<<endl;cout<<"\t* 转账业务*\n"<<endl;cout<<"\t************************************\n"<<endl;cout<<"\t欢迎使用转账业务,请按照提示操作!\n"<<endl;cout<<"\n"<<endl;long cid;long bcid;long psw1;int money1;cout<<"\t\t请输入您的卡号:"<<endl;cin>>cid;cout<<"\t\t请输入您的密码:"<<endl;cin>>psw1;if(cid==cardID && psw1==psw){cout<<"\t\t请输入您要转账的卡号:"<<endl;cin>>bcid;cout<<"\t\t请输入您要转账的金额:"<<endl;cin>>money1;money=money-money1;cout<<"\t\t转账成功!您卡上余额为:"<<money<<endl;}else{cout<<"\t\t您的卡号或者密码错误!"<<endl;}}int print1(){return cardID;}int print2(){return psw;}private:int number;int password;int money;};void main(){ATM per;int i=0,n,psw;int cardID;cout<<"\t*************************************************\n"<<endl;cout<<"\t* ICBC *\n"<<endl;cout<<"\t* 欢迎进入中国工商银行*\n"<<endl;cout<<"\t* ATM自助服务系统*\n"<<endl;cout<<"\t*************************************************\n"<<endl;cout<<"\n"<<endl;cout<<"请输入您的卡号:";cin>>cardID;cout<<"请输入您的密码:";cin>>psw;for(;;){if(cardID==per.print1 () &&psw==per.print2 ()){cout<<"请选择您要办理的手续:\n";cout<<"1.开户\n";cout<<"2.缴费\n";cout<<"3.取款\n";cout<<"4.查询\n";cout<<"5.转账\n";cout<<"6.退出\n";cout<<"请选择你要办理的业务:";cin>>n;if(n==6)break;switch(n){case 1:void openAccount();//开户break;case 2:void saveMoney();//缴费break;case 3:void takeMoney();//取款break;case 4:void query();//查询余额break;case 5:void transfer();//转账default:cout<<"你的输入有误,请输入1--7之间的数:\n";continue;}}else{for(i=1;i<3;i++){cout<<"密码或账号错误,请重新输入"<<endl;cout<<"请输入您的卡号:";cin>>cardID;cout<<"请输入您的密码:";cin>>psw;if(cardID==per.print1 () &&psw==per.print2 ())break;elsecontinue;}if(i==3){cout<<"您的密码尝试次数已达到上限,卡已被系统吞吃。
ATM 需求分析Task 1 .用户界面一个当地银行打算安装一个新的Automated teller machine (A TM)自动取款机,允许用户进行基本的财政交易。
每一个用户只能有一个账户在银行里。
A TM用户应该能够查看他们的账户余额,取钱以及存钱的信息。
A TM的用户界面应该包含下面几个部分:1)一个给用户显示信息的屏幕2)一个接收用户输入数字的键区3)一个出钱的接口,可以出钱币4)一个存储槽能接收用户的存折界面如下图1.1所示。
图1.1 ATM用户界面Task 2. 用户验证A TM的周期包含通过账号和个人身份数字验证用户的有效性,创建和执行财政交易。
为了验证用户以及执行财政交易,A TM需要和存储在电脑上的银行账户信息数据交互。
对于每一个银行账户,数据库存储一个账号,一个密码,一个账户余额。
当第一次接触A TM的时候,用户应该体验下面几个事件:1)屏幕显示欢迎页面,提示用户输入账号。
2) 通过数字键区用户输入五位的账号。
3) 屏幕提示用户输入个人身份数字(密码)4) 用户在键区输入五位的用户身份号码。
5) 如果用户输入有效的账号和正确的密码,屏幕会显示主菜单。
如果用户输入无效的账号或者是错误的密码,屏幕会显示一个错误信息提示用户,然后ATM 返回第一步,重新进行验证的过程。
Task 3. 业务流程在A TM对用户验证后,将会出现主菜单界面。
主菜单应该包含三项操作:查询余额信息,取款和存款。
应该包含另外一个选项就是用户可以退出系统。
用户可以选择其中一项来进行操作(通过输入1,2,3),或者退出系统(通过输入4)。
A TM主界面如下图1.2所示。
图1.2 ATM主界面1.如果用户输入选项1 将查询余额,屏幕将会显示账户里的余额。
这一步是A TM系统从数据库中查询出来然后显示到系统界面上。
2.如果用户输入选项2 取款,以下几个步骤将会描述发生的事件:1)屏幕将会显示一个菜单,菜单包括标准的取款数目,以及取消交易的选项。
Python模拟⾃动存取款机的查询、存取款、修改密码等操作1.⼯作流程2.模拟⾃动存取款机的操作代码如下:import msvcrt, sys, os#定义⽤星号隐藏密码输⼊的函数def psw_input():li = []while True:ch = msvcrt.getch()#回车if ch == b'\r':msvcrt.putch(b'\n')break#退格elif ch == b' 08':if li:li.pop()msvcrt.putch(b'\b')msvcrt.putch(b' ')msvcrt.putch(b'\b')#Escelif ch == b' 1b':breakelse:li.append(ch)msvcrt.putch(b'*')return li#定义CSDN银⾏ATM欢迎界⾯的函数def ATM():'''CSDN银⾏ATM欢迎界⾯的函数'''print("="*14,"Bank of CSDN","="*14,"\n")print("{:^42}".format("ATM"),"\n")print("="*14,"Bank of CSDN","="*14,"\n")#CSDN银⾏⽤户列表信息,⽤户信息包含:姓名、余额、密码(6位)、银⾏卡号(19位)user_list = [{"name":"张三","balance":10000,"password":"000000","numbers":"0000000000000000000"},{"name":"李四","balance":20000,"password":"111111","numbers":"1111111111111111111"},{"name":"王五","balance":30000,"password":"222222","numbers":"2222222222222222222"}]#定义验证银⾏卡号与密码匹配的函数def check(user_name,user_password):'''验证银⾏卡号与密码匹配的函数'''for i in range(len(user_list)):if user_name == user_list[i]["numbers"] and user_password == user_list[i]["password"]:return i #银⾏卡号与密码匹配则返回该⽤户在ATM系统内的ID值,否则返回None值#定义⽤户登录成功后操作界⾯的函数def interface():'''⽤户登录成功后操作界⾯的函数'''print("="*14,"⽤户操作界⾯","="*14,"\n")print("{0:2} {1:12} {2:12} {3:12}".format(" ","1. 查询","2. 取款","3. 存款"),"\n")print("{0:2} {1:10} {2:12}".format(" ","4. 修改密码","5. 退出"),"\n")print("="*42,"\n")#定义⽤户查询信息的函数def inquire(user_id):'''⽤户查询信息的函数'''print("="*14,"账号查询界⾯","="*14,"\n")print("|{0:<4}|{1:<18}|{2:<9}|\n".format("账户名","卡号","余额(RMB)"))print("|{0:<5}|{1:<20}|{2:<11}|\n".format(user_list[user_id]["name"],user_list[user_id]["numbers"],user_list[user_id]["balance"]))#定义⽤户取款的函数def withdrawal(amount):'''⽤户取款的函数'''i = user_list[user_id]["balance"]-int(amount)if i>=0:user_list[user_id]["balance"]-=int(amount)else:print("账户余额不⾜\n")#定义⽤户存款的函数def deposit(amount):'''⽤户存款的函数'''user_list[user_id]["balance"]+=int(amount)#定义⽤户修改密码的函数def change_password(old_password,new_password1,new_password2):'''⽤户修改密码的函数'''if old_password == user_list[user_id]["password"]:if new_password1 == new_password2:user_list[user_id]["password"] = new_password1print("新密码修改成功\n")return 1else:print("修改密码失败,您2次输⼊的新密码不⼀致\n")return 2else:print("旧密码输⼊错误\n")return 0#⽤户登录界⾯,输⼊银⾏卡号和密码chance = 3 #允许3次⽤户名或密码输⼊错误while True:ATM()user_name = input("请输⼊您的银⾏卡卡号:")print("")print("请输⼊您的银⾏卡密码:", end=' ', flush=True)user_password = b''.join(psw_input()).decode()print("")user_id = check(user_name,user_password)#验证银⾏卡号与密码是否匹配if user_id != None:print("登录成功\n")while True:interface()key_word = input("请输⼊操作选项:")print("")if key_word == "1":inquire(user_id)input("按任意键返回上⼀级⽬录:")print("")elif key_word == "2":print("="*14,"账号取款界⾯","="*14,"\n")amount = input("请输⼊取款⾦额:")print("")withdrawal(amount)inquire(user_id)input("按任意键返回上⼀级⽬录:")print("")elif key_word == "3":print("="*14,"账号存款界⾯","="*14,"\n")amount = input("请输⼊存款⾦额:")print("")deposit(amount)inquire(user_id)input("按任意键返回上⼀级⽬录:")print("")elif key_word == "4":print("="*14,"密码管理界⾯","="*14,"\n")print("请输⼊旧密码:", end=' ', flush=True)old_password = b''.join(psw_input()).decode()print("")print("请输⼊新密码:", end=' ', flush=True)new_password1 = b''.join(psw_input()).decode()print("")print("请再次输⼊新密码:", end=' ', flush=True)new_password2 = b''.join(psw_input()).decode()print("")save = change_password(old_password,new_password1,new_password2) #如何检测到旧密码输⼊有误,将直接退出if save == 0:breakelif key_word == "5":print("="*14,"欢迎下次光临","="*14,"\n")breakelse:print("="*14,"没有该选项","="*14,"\n")else:if chance > 1:print("⽤户名或密码错误,您还有",chance-1,"次机会,请重新输⼊\n")chance -= 1else:print("对不起,您输⼊⽤户名或密码错误已达3次")break3.运⾏结果有以下初始⽤户信息备测试⽤:姓名银⾏卡号(19位)密码(6位)余额(RMB)张三 0000000000000000000 000000 10000李四 1111111111111111111 111111 20000王五 2222222222222222222 222222 30000输⼊卡号和密码进⼊⽤户操作界⾯查询余额界⾯取款界⾯存款界⾯修改密码界⾯总结以上所述是⼩编给⼤家介绍的Python模拟⾃动存取款机的查询、存取款、修改密码等操作,希望对⼤家有所帮助,如果⼤家有任何疑问欢迎给我留⾔,⼩编会及时回复⼤家的!。
python模拟银⾏ATM要求:#1.模拟3张银⾏卡,1001,1002,1003分别设置密码和余额(可⽤9个变量分别保存卡号;密码和余额)#2.提⽰⽤户输⼊银⾏卡和密码#3.如果⽤户输⼊正确--提⽰让⽤户选项取款或存款或退卡,并显⽰余额;输⼊错误--重新输⼊卡号密码#4.选项取款--提⽰输⼊取款额度如果超过余额,提⽰余额不⾜,否则,在余额上减掉相应⾦额#5.选项存款--输⼊存款额度,额度加上相应额度并显⽰余额;#6.选项退卡--重新输⼊卡号密码#7.设置3次输⼊错误账号密码,提⽰银⾏卡被冻结card1="1001" #卡号pwd1="" #密码ban1=10000 #余额card2="1002"pwd2=""ban2=10000card3="1003"pwd3=""ban3=10000print("欢迎来到瑞⼠银⾏")times=0 #输⼊密码错误次数while True:card=input("请输⼊您的账号:")pwd=input("请输⼊您的密码")ban=0 #余额if card==card1 and pwd==pwd1:ban=ban1elif card==card2 and pwd==pwd2:ban=ban2elif card==card3 and pwd==pwd3:ban=ban3else:times=times+1if times>=3:print("您的卡已被冻结,请联系银⾏柜台!")breakelse:print("卡号密码输⼊错误!请重新输⼊!")continuewhile True:num=input("请输⼊要办理的业务:1.存款 2.取款 3.退卡")if num=="1":inn=float(input("请输⼊存款⾦额:"))if inn<=0:print("没钱在这浪费什么时间!")continueelif inn>0:ban=ban+innprint("存款成功!存⼊:",inn,"余额",ban)elif num=="2":out=float(input("请输⼊取款⾦额:"))if out>ban:print("年轻⼈赶紧去赚钱,妹⼦都喜欢有钱⼈!")continueelse:ban=ban-outprint("取款成功!取出:",out,"余额",ban)elif num=="3":print("请收好卡⽚,欢迎再来!")breakelse:print("输⼊有误!")continue。
Python实现的银⾏系统模拟程序完整案例本⽂实例讲述了Python实现的银⾏系统模拟程序。
分享给⼤家供⼤家参考,具体如下:银⾏系统模拟程序1、概述使⽤⾯向对象思想模拟⼀个简单的银⾏系统,具备的功能:管理员登录/注销、⽤户开户、登录、找回密码、挂失、改密、查询、存取款、转账等功能。
编程语⾔:python。
2、⽬的通过这个编程练习,可以熟悉运⽤⾯向对象的思想来解决实际问题,其中⽤到的知识点有类的封装、正则表达式、模块等。
3、体会在编写这个程序时,实际上的业务逻辑还是要考虑的,⽐如修改密码时需要输⼊⼿机号、⾝份证号等。
在进⾏类的封装时,实际上还是⽤⾯向过程的思想把⼀些基本的业务逻辑编写成函数,对⼀些重复使⽤的代码也可以封装成函数(就是⾃⼰造适合这个业务的轮⼦,实际开发中很多底层的函数是不⽤⾃⼰再次去实现的,可以直接调⽤),这些都是⼀些底层的封装,然后在实现主要业务时上就可以调⽤类中的⽅法实现,这时只需关注业务逻辑就好了。
使⽤⾯向对象的思想进⾏编程,考虑的点是:实现⼀个功能,有哪些⽅法可以让我进⾏调⽤(指挥者)。
使⽤⾯向过程的思想进⾏编程,考虑的点是:实现⼀个功能,我需要实现哪些⽅法(执⾏者)。
编写这个程序还⽤到⼀个很重要的概念,就是对程序进⾏模块化。
模块化的好处是可以更好的对程序进⾏维护,条理也更清晰。
4、代码1、bankSystem.py⽂件from view import Viewfrom atm import ATMfrom person import Persondef func(view,atm,per):view.funcInterface()choice = input("请选择您要办理的业务:")if choice == '1':return per.checkMoney(atm)elif choice == '2':return per.saveMoney(atm)elif choice == '3':return per.getMoney(atm)elif choice == '4':return per.transferMoney(atm)elif choice == '5':return per.changePassword(atm)elif choice == '6':return per.unlockAccount(atm)elif choice == '7':return per.closeAccount(atm)elif choice == 'T':if per.exit(atm):return Trueelse:print("输⼊有误!")def main():# 管理员登录名为'admin',密码为'123'view = View("admin",'123')view.initface()atm = ATM()view.login()per = Person()while True:view.funcInit()choice = input("请选择您要办理的业务:")if choice == '1':per.newAccount(atm)elif choice == '2':if per.login(atm):while True:if func(view,atm,per) == None:continueelse:breakelif choice == '3':per.findBackPassword(atm)elif choice == '4':per.lockAccount(atm)elif choice == 'T':if per.exit(atm):# 管理员注销系统if view.logout():return Trueelse:print("输⼊有误!")if __name__ == '__main__':main()2、card.py⽂件:'''卡:类名:Card属性:卡号【6位随机】密码余额绑定的⾝份证号⼿机号'''class Card(object):def __init__(self, cardId, password, money,identityId,phoneNum,cardLock='False'):self.cardId = cardIdself.password = passwordself.money = moneyself.identityId = identityIdself.phoneNum = phoneNumself.cardLock = cardLock3、readAppendCard.py⽂件:'''功能:读取⽂件cardInfo.txt的信息⽅法:读、写、删'''from card import Cardimport json# 读class ReadCard(Card):def __init__(self, cardId='', password='', money=0, identityId='', phoneNum='', cardLock=''):Card.__init__(self, cardId, password, money, identityId, phoneNum, cardLock)def dict2Card(self, d):return self.__class__(d["cardId"], d["password"], d["money"],d["identityId"],d["phoneNum"], d["cardLock"]) def read(self):# card对象转为字典with open("cardinfo.txt","r",encoding="utf-8") as fr:cards = []for re in fr.readlines():cards.append(self.dict2Card(eval(re)))return cards# 写class AppendCard(Card):def __init__(self):Card.__init__(self, cardId = '', password = '', money = 0, identityId = '', phoneNum = '', cardLock='')def card2Dict(self,card):return {"cardId": card.cardId, "password": card.password,"money": card.money, "identityId": card.identityId,"phoneNum": card.phoneNum, "cardLock": card.cardLock}def append(self,card,w= 'a'):# 默认是追加,如果w='w'就清空⽂件if w == 'w':with open("cardinfo.txt", "w", encoding="utf-8") as fa:fa.write('')else:with open("cardinfo.txt", "a", encoding="utf-8") as fa:json.dump(card, fa, default=self.card2Dict)fa.write('\n')# 删class Del(object):def del_(self,cardId):readcard = ReadCard()cards = readcard.read()for card in cards:# 删除输⼊的卡号if cardId == card.cardId:cards.remove(card)breakelse:print("卡号不存在!")return False# 重新写⼊⽂件appendcard = AppendCard()appendcard.append('',w='w')for card in cards:appendcard.append(card)return True4、person.py'''⼈类名:Person⾏为:开户、查询、取款、存储、转账、改密、销户、退出'''class Person(object):def __init__(self,name='',identity='',phoneNum='',card=None): = nameself.identity = identityself.phoneNum = phoneNumself.card = card# 登录def login(self,atm):card = atm.login()if card:self.card = cardreturn Trueelse:return False# 开户def newAccount(self,atm):return atm.newAccount()#找回密码def findBackPassword(self,atm):return atm.findBackPassword()# 查询余额def checkMoney(self, atm):return atm.checkMoney(self.card)# 存钱def saveMoney(self, atm):return atm.saveMoney(self.card)# 取钱def getMoney(self, atm):return atm.getMoney(self.card)# 转账def transferMoney(self, atm):return atm.transferMoney(self.card)# 销户def closeAccount(self, atm):return atm.closeAccount(self.card)# 挂失def lockAccount(self, atm):return atm.lockAccount()# 解锁def unlockAccount(self, atm):return atm.unlockAccount(self.card)# 改密def changePassword(self, atm):return atm.changePassword(self.card)# 退出系统def exit(self, atm):return atm.exit()5、view.py'''管理员界⾯类名:View属性:账号,密码⾏为:管理员初始化界⾯管理员登陆系统功能界⾯管理员注销系统功能:开户查询取款存储转账改密销户退出'''from check import Checkimport timeclass View(object):def __init__(self,admin,password):self.admin = adminself.password = password# 管理员初始化界⾯def initface(self):print("*------------------------------------*")print("| |")print("| 管理员界⾯正在启动,请稍候... |")print("| |")print("*------------------------------------*")time.sleep(1)return#管理员登录界⾯def login(self):print("*------------------------------------*")print("| |")print("| 管理员登陆界⾯ |")print("| |")print("*------------------------------------*")check = Check()erName(self.admin,self.password)print("*-------------登陆成功---------------*")print(" 正在跳转到系统功能界⾯,请稍候... ")del checktime.sleep(1)return# 管理员注销界⾯def logout(self):print("*------------------------------------*")print("| |")print("| 管理员注销界⾯ |")print("| |")print("*------------------------------------*")#确认是否注销check = Check()if not check.isSure('注销'):return FalseerName(self.admin,self.password)print("*-------------注销成功---------------*")print(" 正在关闭系统,请稍候... ")del checktime.sleep(1)return True#系统功能界⾯'''系统功能:开户,查询,取款,存储,转账,销户,挂失,解锁,改密,退出 '''def funcInit(self):print("*-------Welcome To Future Bank---------*")print("| |")print("| (1)开户 (2)登录 |")print("| (3)找回密码 (4)挂失 |")print("| (T)退出 |")print("| |")print("*--------------------------------------*")def funcInterface(self):print("*-------Welcome To Future Bank---------*")print("| |")print("| (1)查询 (5)改密 |")print("| (2)存款 (6)解锁 |")print("| (3)取款 (7)销户 |")print("| (4)转账 (T)退出 |")print("| |")print("*--------------------------------------*")6、atm.py'''提款机:类名:ATM属性:⾏为(被动执⾏操作):开户,查询,取款,存储,转账,销户,挂失,解锁,改密,退出'''from check import Checkfrom card import Cardfrom readAppendCard import ReadCard,AppendCardimport randomimport timeclass ATM(object):def __init__(self):# 实例化相关的类self.check = Check()self.readCard = ReadCard()self.appendCard = AppendCard()self.cards = self.readCard.read()# 显⽰功能界⾯def funcShow(self,ope):if ope != "找回密码":print("*-------Welcome To Future Bank-------*")print("| %s功能界⾯ |"%ope)print("*------------------------------------*")else:# 显⽰找回密码界⾯print("*-------Welcome To Future Bank-------*")print("| 找回密码功能界⾯ |")print("*------------------------------------*")# 卡号输⼊def cardInput(self,ope=''):while True:cardId = input("请输⼊卡号:")password = input("请输⼊密码:")card = self.check.isCardAndPasswordSure(self.cards, cardId,password) if not card:print("卡号或密码输⼊有误")if ope == 'login' or ope == 'lock':return Falseelse:continueelse:return card# 登录def login(self):self.funcShow("登录")return self.cardInput('login')#找回密码def findBackPassword(self):self.funcShow("找回密码")cardId = input("请输⼊卡号:")card = self.check.isCardIdExist(self.cards,cardId)if card:if not self.check.isCardInfoSure(card,"找回密码"):returnnewpassword = self.check.newPasswordInput()index = self.cards.index(card)self.cards[index].password = newpasswordself.writeCard()print("找回密码成功!请重新登录")time.sleep(1)return Trueelse:print("卡号不存在")return True# 开户def newAccount(self):self.funcShow("开户")# 输⼊⾝份证号和⼿机号pnum = self.check.phoneInput()iden = self.check.identifyInput()print("正在执⾏开户程序,请稍候...")while True:# 随机⽣成6位卡号cardId = str(random.randrange(100000, 1000000))# 随机⽣成的卡号存在就继续if self.check.isCardIdExist(self.cards,cardId):continueelse:break# 初始化卡号密码,卡⾥的钱,卡的锁定状态card = Card(cardId, '888888', 0, iden, pnum , 'False')self.appendCard.append(card)print("开户成功,您的卡号为%s,密码为%s,卡余额为%d元!"%(cardId,'888888',0)) print("为了账户安全,请及时修改密码")# 更新卡号列表self.cards = self.readCard.read()return True# 查询def checkMoney(self,card):self.funcShow("查询")if self.check.isCardLock(card):print("查询失败!")else:print("卡上余额为%d元!" %card.money)time.sleep(1)# 存款def saveMoney(self,card):self.funcShow("存款")if self.check.isCardLock(card):print("存钱失败!")else:mon = self.check.moneyInput("存款")# 找到所有卡中对应的卡号,然后对此卡进⾏存款操作index = self.cards.index(card)self.cards[index].money += monprint("正在执⾏存款程序,请稍候...")time.sleep(1)self.writeCard()print("存款成功!卡上余额为%d元!"%self.cards[index].money)time.sleep(1)# 取款def getMoney(self,card):self.funcShow("取款")if self.check.isCardLock(card):print("取钱失败!")else:print("卡上余额为%d元!" %card.money)mon = self.check.moneyInput("取款")if mon:if mon > card.money:print("余额不⾜,您当前余额为%d元!"%card.money)time.sleep(1)else:print("正在执⾏取款程序,请稍候...")time.sleep(1)# 找到所有卡中对应的卡号,然后对此卡进⾏存款操作index = self.cards.index(card)self.cards[index].money -= monself.writeCard()print("取款成功!卡上的余额为%d元!"%self.cards[index].money)time.sleep(1)# 转账def transferMoney(self,card):self.funcShow("转账")if self.check.isCardLock(card): #如果卡已锁定就不能进⾏转账操作print("转账失败!")returnwhile True:cardId = input("请输⼊对⽅的账号:")if cardId == card.cardId:print("不能给⾃⼰转账")returncardOther = self.check.isCardIdExist(self.cards,cardId) #判断对⽅卡号是否存在if cardOther == False:print("对⽅账号不存在")returnelse:breakwhile True:print("卡上余额为%d元"%card.money)mon = self.check.moneyInput("转账")if not mon: #输⼊的⾦额不对就返回returnif mon > card.money: #输⼊的⾦额⼤于卡上余额就返回print("余额不⾜,卡上余额为%d元!" % card.money)returnelse:breakprint("正在执⾏转账程序,请稍候...")time.sleep(1)index = self.cards.index(card) # 找到所有卡中对应的卡号,然后对此卡进⾏转账操作 self.cards[index].money -= monindexOther = self.cards.index(cardOther) #找到对卡卡号所处位置self.cards[indexOther].money += monself.writeCard()print("转账成功!卡上余额为%d元!" % self.cards[index].money)time.sleep(1)# 销户def closeAccount(self,card):self.funcShow("销户")if not self.check.isCardInfoSure(card,"销户"):returnif card.money >0:print("卡上还有余额,不能进⾏销户")returnif self.check.isSure("销户"):self.cards.remove(card) #移除当前卡号self.writeCard()print("销户成功!")time.sleep(1)return True# 挂失def lockAccount(self):self.funcShow("挂失")card = self.cardInput('lock')if not card:returnif card.cardLock == "True":print("卡已处于锁定状态")returnif not self.check.isCardInfoSure(card,"挂失"):returnif self.check.isSure("挂失"):index = self.cards.index(card) #找到所有卡中对应的卡号,然后对此卡进⾏挂失操作 self.cards[index].cardLock = "True"self.writeCard()print("挂失成功!")time.sleep(1)return True# 解锁def unlockAccount(self,card):self.funcShow("解锁")if card.cardLock == 'False':print("⽆需解锁,卡处于正常状态")returnif not self.check.isCardInfoSure(card,"解锁"):returnindex = self.cards.index(card)self.cards[index].cardLock = "False"self.writeCard()print("解锁成功!")time.sleep(1)return True# 改密def changePassword(self,card):self.funcShow("改密")if self.check.isCardLock(card):print("卡处于锁定状态,不能进⾏改密")returnif not self.check.isCardInfoSure(card,"改密"):return# 输⼊旧密码while True:password = input("请输⼊旧密码:")if self.check.isPasswordSure(password,card.password):breakelse:print("卡号原密码输⼊错误!")returnnewpassword = self.check.newPasswordInput()index = self.cards.index(card) #找到所有卡中对应的卡号,然后对此卡进⾏改密操作 self.cards[index].password = newpasswordself.writeCard()print("改密成功!请重新登录")time.sleep(1)return True# 写⼊⽂件def writeCard(self):self.appendCard.append('', w='w') #先清除原⽂件再重新写⼊for card in self.cards:self.appendCard.append(card)# 退出def exit(self):if self.check.isSure("退出"):return Trueelse:return False7、check.py'''验证类:⽤户名、密码、卡号、⾝份证、⼿机号验证使⽤正则表达式进⾏⽂本搜索'''import reclass Check(object):def __init__(self):pass#⽤户验证def userName(self,admin,password):self.admin = adminself.password = passwordwhile True:admin = input("请输⼊⽤户名:")password = input("请输⼊密码:")if admin != self.admin or password != self.password:print("⽤户名或密码输⼊有误,请重新输⼊")continueelse:return#是否确认某操作def isSure(self,operate):while True:res = input("是否确认%s?【yes/no】"%operate)if res not in ['yes','no']:print("输⼊有误,请重新输⼊")continueelif res == 'yes':return Trueelse:return False# ⼿机号验证def phoneInput(self):# 简单的⼿机号验证:开头为1且全部为数字,长度为11位while True:pnum = input("请输⼊您的⼿机号:")res = re.match(r"^1\d{10}$",pnum)if not res:print("⼿机号输⼊有误,请重新输⼊")continuereturn pnum# ⾝份证号验证def identifyInput(self):# 简单的⾝份证号验证:6位,只有最后⼀可以为x,其余必须为数字while True:iden = input("请输⼊您的⾝份证号(6位数字):")res = re.match(r"\d{5}\d|x$",iden)if not res:print("⾝份证号输⼊有误,请重新输⼊")continuereturn iden# 卡号是否存在def isCardIdExist(self,cards,cardId):for card in cards:if cardId == card.cardId:return cardelse:return False# 卡号和密码是否⼀致def isCardAndPasswordSure(self,cards,cardId,password):card = self.isCardIdExist(cards,cardId)if card:if card.password == password:return cardreturn False# 密码⼆次确认是否正确def isPasswordSure(self, newassword,oldpassword):if newassword == oldpassword:return Trueelse:return False# 卡号完整信息验证def isCardInfoSure(self,card,ope):phoneNum = input("请输⼊⼿机号:")iden = input("请输⼊⾝份证号:")if card.phoneNum == phoneNum and card.identityId == iden:return Trueprint("%s失败\n密码、⼿机号或⾝份证号与卡中绑定的信息不⼀致"%ope)return False# 卡号是否锁定def isCardLock(self,card):if card.cardLock == "True":print("此卡已挂失!")return Truereturn False# 输⼊⾦额验证def moneyInput(self,ope):mon = input("输⼊%s⾦额(100的倍数):"%ope)# 输⼊的钱必须是100的倍数if re.match(r"[123456789]\d*[0]{2}$", mon):return int(mon)print("输⼊有误,%s⾦额必须是100的倍数!请重新输⼊"%ope)return Falsedef newPasswordInput(self):while True:newpassword = input("请输⼊新密码:")if not re.match(r"\d{6}$",newpassword):print("密码必须是6位的纯数字")continuenewpasswordAgain = input("请重复输⼊新密码:")if self.isPasswordSure(newpassword, newpasswordAgain):breakelse:print("两次输⼊不⼀致!")continuereturn newpassword更多关于Python相关内容感兴趣的读者可查看本站专题:《》、《》、《》、《》、《》及《》希望本⽂所述对⼤家Python程序设计有所帮助。
一、实验目的1.函数的调用2.结构体的使用3.文件的应用:打开、关闭、输入、输出等4.宏定义二、实验内容与实验步骤实验内容、原理分析1.给出数据结构或函数定义结构体:struct clients{long int card_number,card_password;char name[20];float money;}yonghu[3];card_number:银行卡号card_password:密码name:用户名money:卡内金额自定义函数:void fuction(float,int);用于登陆后的操作2.用流程图表示出来程序设计的思想3.#include <stdio.h> #include <stdlib.h> #defineN3/*用户人数*/struct clients { long int card_number,card_password;char name[20]; float money; }yonghu[N]; FILE *fp; int i;void fuction(float,int); void main() { int j,number,password,times1=3,times2=3; printf("欢迎使用A TM 自动取款机!\n"); fp = fopen("clients.dat","a+"); if(getw(fp)==EOF) {printf("用户文件未设置!\n");for(i=0;i<N;i++) /*文件不存在时,输入用户信息*/ { printf("请输入第%d 位用户的信息:\n",i+1);printf("银行卡号 密码 用户名 卡内金额\n");scanf("%d %d %s %f",&yonghu[i].card_number,&yonghu[i].card_password,yonghu[i].name,&yonghu[i].money); if(i==1) {while((yonghu[i].card_number==yonghu[i-1].card_number)||(yonghu[i].card_password==yonghu[i-1].card_password)) { printf("输入信息有重复!请重新输入\n"); printf("请输入第%d 位用户的信息:\n",i+1);printf("银行卡号 密码 用户名 卡内金额\n");scanf("%d %d %s %f",&yonghu[i].card_number,&yonghu[i].card_password,yonghu[i].name ,&yonghu[i].money);}}if(i==2){while((yonghu[i].card_number==yonghu[i-1].card_number)||(yonghu[i].card_password==yo nghu[i-1].card_password)||(yonghu[i].card_number==yonghu[i-2].card_number)||(yonghu[i].card_ password==yonghu[i-2].card_password)){printf("输入信息有重复!请重新输入\n");printf("请输入第%d位用户的信息:\n",i+1);printf("银行卡号密码用户名卡内金额\n");scanf("%d %d %s %f",&yonghu[i].card_number,&yonghu[i].card_password,yonghu[i].name ,&yonghu[i].money);}}fprintf(fp,"%d %d %s %f",yonghu[i].card_number,yonghu[i].card_password,yonghu[i].name ,yonghu[i].money);putc('\n',fp);}}fclose(fp);printf("\n\n 请登录系统\n"); /*登录系统,输入卡号和密码*/printf("请输入您的银行卡号:\n");scanf("%d",&number);printf("请输入您的密码:\n");scanf("%d",&password);fp = fopen("clients.dat","r+");for(i=0;i<N;i++){fscanf(fp,"%d %d %s %f",&yonghu[i].card_number,&yonghu[i].card_password,yonghu[i].na me,&yonghu[i].money);}fclose(fp);for(i=0;i<N;i++)/*判断卡号及密码是否匹配*/{if((number!=yonghu[0].card_number)&&(number!=yonghu[1].card_number)&&(number!=y onghu[2].card_number)){if((times1-1)!=0){printf("该用户不存在!您还有%d次尝试机会\n",times1-1);printf("请输入您的银行卡号:\n");scanf("%d",&number);printf("请输入您的密码:\n");scanf("%d",&password);i=-1;}else{printf("尝试失败!请按任意键退出:\n");exit(0);}times1--;}else{if(number==yonghu[i].card_number){if(password==yonghu[i].card_password){printf(" %s登陆成功!请继续您的操作\n",yonghu[i].name);j=i;i=5;/*登陆成功,退出循环*/}else{if((times2-1)!=0){printf("密码输入错误!您还有%d次尝试机会\n",times2-1);printf("请输入您的密码:\n");scanf("%d",&password);i=-1;}else{printf("尝试失败!请按任意键退出:\n");exit(0);}times2--;}}}}fuction(yonghu[j].money,j);}void fuction(float m,int k){float saved_money,fetched_money;int x;while(1){printf("1.存款.\n2.取款.\n3.查询.\n0.退出系统.\n");scanf("%d",&x);switch(x){case 0:printf("退出系统!");exit(0);case 1:printf("请输入存款金额:\n");scanf("%f",&saved_money);while(saved_money<0){printf("输入有误!请重新输入!\n");printf("请输入存款金额:\n");scanf("%f",&saved_money);}m += saved_money;printf("操作成功!卡内余额为: %f\n",m);yonghu[k].money = m;fp = fopen("clients.dat","w+");for(i=0;i<N;i++){fprintf(fp,"%d %d %s %f",yonghu[i].card_number,yonghu[i].card_password,yonghu[i].name ,yonghu[i].money);putc('\n',fp);}fclose(fp);break;case 2:printf("请输入取款金额:\n");scanf("%f",&fetched_money);m -= fetched_money;while((fetched_money<0)||(m<0)){printf("输入有误!请重新输入!\n");m += fetched_money;printf("请输入取款金额:\n");scanf("%f",&fetched_money);m -= fetched_money;}printf("操作成功!卡内余额为: %f\n",m);yonghu[k].money = m;fp = fopen("clients.txt","w+");for(i=0;i<N;i++){fprintf(fp,"%d %d %s %f",yonghu[i].card_number,yonghu[i].card_password,yonghu[i].name ,yonghu[i].money);putc('\n',fp);}fclose(fp);break;case 3:printf("卡内金额: %f\n",m);break;default:printf("输入有误!请重新输入!\n");break;}}}三、实验过程与结果分析1.现象:输入用户信息后,在登录系统时,输入第一个用户的信息,提示该用户不存在解决方法:fp = fopen("clients.txt","r+");for(i=0;i<N;i++){fscanf(fp,"%d %d %s %f",&yonghu[i].card_number,&yonghu[i].card_password, yonghu[i].name,&yonghu[i].money);}fclose(fp);2.现象:登录系统时,输入卡号或密码超过3次错误后,仍能输入解决方法:增加变量times1=3(卡号输入错误的次数),times2=3(密码输入错误的次数),当times-1>0时,提示剩余尝试机会,当times-1=0时,退出程序3.现象:存取款或充话费时,输入负数仍能运行解决方法:增加循环:while(saved_money<0){printf("输入有误!请重新输入!\n");printf("请输入存款金额:\n");scanf("%f",&saved_money);}while((fetched_money<0)||(m<0)){printf("输入有误!请重新输入!\n");m += fetched_money;printf("请输入取款金额:\n");scanf("%f",&fetched_money);m -= fetched_money;}while((payment<0)||(m<0)){printf("输入有误!请重新输入!\n");m += payment;printf("请输入所交话费金额:\n");scanf("%f",&payment);m -= payment;}四、实验结果总结。
python实现atm机基本操作及购物车⼀.需求分析 ATM机要为⽤户提供转账,提现,还款,付款,消费流⽔,操作记录等操作接⼝ ATM机要为管理员提供创建⽤户,冻结解冻,修改额度的功能 ATM机管理员认证使⽤装饰器来实现 购物车要提供管理员和⽤户两个接⼝ ⽤户接⼝需要提供,查询余额,充值,查询⽤户消费记录,购物等操作接⼝ 商户接⼝需要提供,上架,下架,修改,查看上架货品等操作接⼝⼆.流程图三.代码实现 ⼯程的创建按照较为简便的格式来描述,⼤致⽬录结构如图:ATMandShopCar/|-- bin/| |--|-- DataAccess| |--ATM_UserCard.txt| |--ATM_UserInfo.txt| |--ATM_UserOpt.txt| |--goods_info.txt| |--users_info.txt| |--users_value.txt| |-- ShopingCar/| |-- tests/| | |-- __init__.py| | |-- test_main.py| |--ATM.py| |--DataAccess.py| |--ShoopingCar.py| |-- __init__.py| |-- main.py||-- docs/| |-- conf.py| |-- abc.rst||-- setup.py|-- requirements.txt|-- README 上述⽬录中最主要的部分是:DataAccess和ShopingCar两个⽂件夹,DataAccess主要存放⽤户操作数据,俗称数据库,本⼯程使⽤⽂本作为存储数据的载体。
ShopingCar为程序处理.py,DataAccess.py主要⽤于 DataAccess.py程序代码如下:import osimport timeBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+'/DataAccess/'#设置路径user_status = False# ⽤户转账接⼝def ATM_UserTranster(UserID):#⽤户转账接⼝#此程序接⼝不适⽤与管理数据量较⼤的数据,采⽤的是⼀次读取⽂件所有数据操作⽅式with open(BASE_DIR +'ATM_Useropt.txt', 'a')as f:info = UserID + '' + '转账' + '' + time.strftime('%Y-%m-%d-%X') + '\n'f.write(info)a = []with open(BASE_DIR + 'ATM_UserCard.txt', 'r') as f:for line in f:a.append(line.strip().split(''))for i,index in enumerate(a):if index[0] == UserID:if index[4] == '0':print("当前账户被冻结,⽆法转账!")returnBalance = int(index[5])pos=iprint("账户\033[32;1m%s\033[0m可供转账余额为 :%s" % (UserID, Balance))breakwhile True:UserCardID = input('请输⼊待转账⽤户卡号输⼊q退出 :')if UserCardID.isdigit():for index in a :if index[0] == UserCardID:Value = input("请输⼊转账⾦额输q退出:")if Value.isdigit():Value = int(Value)if Value>Balance:print("操作失败,余额不⾜!")else:index[5]=str(int(index[5])+Value)a[pos][5]=str(Balance-Value)f.write(''.join(line)+'\n')print("转账成功!当前账户余额为 :\033[32;1m%s\033[0m"%a[pos][5])returnelif'q' == Value:breakelse:passelif'q' == UserCardID:breakelse:pass#提现接⼝def ATM_UserWithdrawal(UserID):with open(BASE_DIR +'ATM_Useropt.txt', 'a')as f:info = UserID+ ''+'提现' + '' + time.strftime('%Y-%m-%d-%X') + '\n'f.write(info)a = []with open(BASE_DIR + 'ATM_UserCard.txt', 'r') as f:for line in f:a.append(line.strip().split(''))for i,index in enumerate(a):if index[0] == UserID:if index[4] == '0':print("当前账户被冻结,⽆法提现!")returnBalance = int(index[5])print("账户\033[32;1m%s\033[0m可供提现⾦额为 :%s" % (UserID, Balance))breakwhile True:Value=input("请输⼊要提现的⾦额输⼊q退出:")if Value.isdigit():Value = int(Value)if Value>Balance:print("余额不⾜,提现失败")else:Balance = Balance-Valueprint("提现成功,账户余额为 \033[32;1m%s\033[0m"%Balance)elif'q'==Value:index[5] = str(Balance)with open(BASE_DIR + 'ATM_UserCard.txt', 'w') as f:for line in a:f.write(''.join(line) + '\n')print("谢谢使⽤!")returnbreakelse:pass#流⽔def ATM_UserWater(UserName,UserID):with open(BASE_DIR + 'ATM_Useropt.txt', 'a')as f:info = UserID + '' + '查流⽔' + '' + time.strftime('%Y-%m-%d-%X') + '\n'f.write(info)user_info = []with open(BASE_DIR + 'ATM_UserInfo.txt', 'r')as f:for line in f:user_info.append(line.strip().split(''))T = Falsefor line in user_info:if UserName == line[0]:T = Trueprint('⽤户 :\033[32;1m%s\033[0m 购物清单 :%s 消费 :%s ⽇期 :%s' % (line[0], line[1], line[2], line[3])) if T == False:print("⽤户\033[32;1m%s\033[0m⽆消费记录!" % UserName)#操作记录def ATM_UserOpt(UserID):with open(BASE_DIR + 'ATM_Useropt.txt', 'a')as f:info = UserID + '' + '查操作记录' + '' + time.strftime('%Y-%m-%d-%X') + '\n'f.write(info)user_info = []with open(BASE_DIR + 'ATM_Useropt.txt', 'r')as f:for line in f:user_info.append(line.strip().split(''))T = Falsefor line in user_info:if UserID == line[0]:T = Trueprint('⽤户 :\033[32;1m%s\033[0m 操作内容 :%s ⽇期 :%s' % (line[0],line[1],line[2]))if T == False:print("⽤户\033[32;1m%s\033[0m ⽆操作记录!" % UserID)#还款接⼝def ATM_UserReimbursement(UserID):with open(BASE_DIR + 'ATM_Useropt.txt', 'a')as f:info = UserID + '' + '还款' + '' + time.strftime('%Y-%m-%d-%X') + '\n'f.write(info)a = []with open(BASE_DIR + 'ATM_UserCard.txt', 'r') as f:for line in f:a.append(line.strip().split(''))for i, index in enumerate(a):if index[0] == UserID:if index[4] == '0':print("当前账户被冻结,⽆法操作!")if Balance<0:print("账户\033[32;1m%s\033[0m⽆需还款!"%UserID)returnprint("账户\033[32;1m%s\033[0m需要还款⾦额为 :%s" % (UserID, Balance))breakwhile True:Value = input("请输⼊还款⾦额输⼊q退出 :")if Value.isdigit():Value = int(Value)if(int(index[5])+Value)>int(index[3]):index[5] = str(int(index[5])+Value)print("还款成功,当前账户活期余额为 :%s,剩余可⽤信⽤额度为 :%s"%(int(index[5])-int(index[3]),index[3])) else:index[5] = str(int(index[5]) + Value)print("还需还款⾦额为 :%s,当前可⽤额度为 :%s" %(int(index[3])-int(index[5]),index[5])) elif Value=='q':with open(BASE_DIR + 'ATM_UserCard.txt', 'w') as f:for line in a:f.write(''.join(line) + '\n')print("谢谢使⽤!")breakelse:pass# ⽤户刷卡接⼝# 参数:Count_Value消费⾦额def ATM_ExpensePort(Count_Value):UserInfo = []with open(BASE_DIR + 'ATM_UserCard.txt', 'r') as f:for line in f:UserInfo.append(line.strip().split(''))while True:UserID = input("请输⼊账户名称:")Password = input("请输⼊密码:")t = Truefor line in UserInfo:if line[0] == UserID and line[1] == Password:t = Falseif line[4] == '1':print("账户当前可⽤额度为:\033[32;1m%s\033[0m" % line[5])if int(Count_Value) > int(line[5]):print("账户额度不⾜!")else:line[5] = str(int(line[5]) - int(Count_Value))print("此次消费:\033[32;1m%s\033[0m,当前额度为:\033[32;1m%s\033[0m" % (Count_Value, line[5])) with open(BASE_DIR + 'ATM_UserCard.txt', 'w')as f:for line in UserInfo:f.write(''.join(line) + '\n')return Trueelse:print("帐号已被封锁,请到柜台处理!")return Falseif t == True:print("账户或密码错误!")pass#认证装饰器def login(func):def inuc(*args, **kwargs):_username = "alex"# 假装这是DB⾥存的⽤户信息_password = "123456"# 假装这是DB⾥存的⽤户信息global user_statusif user_status == False:username = input("username:")password = input("password:")if username == _username and password == _password:print("登⼊成功!")user_status = Trueif user_status == True:func(*args, **kwargs)return inuc#添加账户@logindef ATM_UserAdd():a=[]with open(BASE_DIR + 'ATM_UserCard.txt', 'r') as f:for line in f:a.append(line.strip().split(''))while True:Value = input("请输⼊要注册的账号,密码,⽤户名,以逗号隔开,输⼊q退出 :")if Value =='q':breakelse:b=Value.split(',')f = Truefor line in a:if line[0]==b[0]:f = Falsebreakif f==False:print("账户已存在!")passwith open(BASE_DIR + 'ATM_UserCard.txt','a')as f:f.write(''.join(b) + '\n')print("⽤户注册成功!")break#⽤户额度管理@logindef Account_Manage():a = []with open(BASE_DIR + 'ATM_UserCard.txt', 'r') as f:for line in f:a.append(line.strip().split(''))Over_Flag = Falsewhile True:if Over_Flag == True:breakUserId = input("请输⼊⽤户账户:")if UserId.isdigit():F = Falsefor line in a:if UserId == line[0]:F = Trueprint("⽤户当前额度为:\033[32;1m%s\033[0m"%line[3])while True:Value = input("请输⼊更新额度,输⼊q退出:")if Value.isdigit():line[3] = Valueprint("额度修改成功!")elif Value=='q':with open(BASE_DIR + 'ATM_UserCard.txt','w')as f:for lines in a:f.write(''.join(lines)+'\n')Over_Flag = Truebreakelse:print("输⼊有误!")breakif F == False:print("账户不存在!")elif UserId == 'q':breakelse:print("输⼊有误!")pass#账户冻结@logindef user_freeze():a=[]with open(BASE_DIR + 'ATM_UserCard.txt', 'r') as f:for line in f:a.append(line.strip().split(''))while True:UserId = input("请输⼊⽤户账户:")if UserId.isdigit():for line in a:if UserId == line[0]:if line[4]=='1':print("账户当前状态为:\033[32;1m%s\033[0m" %('正常'))else:print("账户当前状态为:\033[32;1m%s\033[0m" %('冻结'))while True:Flag = input("1.冻结,2.解冻,q.退出:")if Flag.isdigit():if Flag =='1':line[4] = '0'print("该账户已冻结!")elif Flag =='2':line[4] = '1'print("该账户已解冻!")else:passelif Flag == 'q':with open(BASE_DIR + 'ATM_UserCard.txt','w')as f:for lines in a:f.write(''.join(lines)+'\n')breakelse:passelif Flag == 'q':breakelse:pass#查询数据库中的数据def search_data_access():goods=[]with open(BASE_DIR+'goods_info.txt','r')as f:for line in f:goods.append(line.strip().split(''))for i in range(len(goods)):print('%s 价格 :%s 库存 :%s'%(goods[i][0],goods[i][1],goods[i][2])) #添加商品操作#参数说明:goodname 商品名 prace 价格 Num 库存量with open(BASE_DIR+'goods_info.txt','r')as f:for line in f:goods.append(line.strip().split(''))T = Falsefor line in goods:if line[0] == GoodName:T = Trueprint("商品已存在,添加失败!")returnInfo = GoodName+''+str(prace)+''+str(Num)+'\n'with open(BASE_DIR + 'goods_info.txt', 'a')as f:f.write(Info)print("添加商品%s成功!" %GoodName )#删除商品操作def delet_goods_opt(GoodName):goods=[]with open(BASE_DIR+'goods_info.txt','r')as f:for line in f:goods.append(line.strip().split(''))for line in goods:if GoodName == line[0]:print("删除商品%s成功!"%line[0])goods.remove(line)with open(BASE_DIR + 'goods_info.txt', 'w')as f:for line in goods:f.write(''.join(line) + '\n')returnprint("没有此商品信息,删除失败!")#修改商品参数#参数说明:goodname 商品名 prace 价格 Num 库存量def Change_goods_info(GoodName,prace,Num):goods = []with open(BASE_DIR+'goods_info.txt','r')as f:for line in f:goods.append(line.strip().split(''))for line in goods:if line[0] == GoodName:line[1] = str(prace)line[2] = str(Num)with open(BASE_DIR+'goods_info.txt','w')as f:for lines in goods:f.write(''.join(lines) + '\n')print("商品%s参数修改成功!"%(GoodName))returnprint("数据库中没有此商品,修改失败!")#查⽤户余额def user_printAccountBalance(UserName):user_info=[]with open(BASE_DIR + 'users_value.txt', 'r')as f:for line in f:user_info.append(line.strip().split(''))for line in user_info:if line[0] == UserName:print("\033[32;1m%s\033[0m的账户余额 :\033[32;1m%s\033[0m"%(UserName,line[1]))return#充值# UserName :⽤户名,充值⾦额:新⽼⽤户标识新⽤户为True⽼⽤户为Falsedef user_TopUp(UserName,Value):user_info = []with open(BASE_DIR+'users_value.txt', 'r')as f:for line in f:user_info.append(line.strip().split(''))for line in user_info:if line[0] == UserName:line[1]=str(int(line[1])+Value)with open(BASE_DIR+'users_value.txt', 'w')as f:for lines in user_info:f.write(''.join(line) + '\n')print("充值成功\033[32;1m%s\033[0m当前的账户余额 :\033[32;1m%s\033[0m" % (UserName, line[1])) returnuser_info = UserName + '' + str(Value) + '\n'with open(BASE_DIR + 'users_value.txt', 'a')as f:f.write(user_info)print("新⽤户充值成功\033[32;1m%s\033[0m当前的账户余额 :\033[32;1m%s\033[0m" % (UserName, Value)) #查询⽤户消费记录def user_RecordsConsumption(UserName):user_info = []with open(BASE_DIR+'users_info.txt', 'r')as f:for line in f:user_info.append(line.strip().split(''))T = Falsefor line in user_info:if UserName == line[0]:T=Trueprint('⽤户 :\033[32;1m%s\033[0m 购物清单 :%s 消费 :%s ⽇期 :%s'%(line[0],line[1],line[2],line[3]))if T==False:print("⽤户\033[32;1m%s\033[0m⽆消费记录!"%UserName)#购物车def user_ShoopCar(Username):goods_info = []ShoopCar = [] # 创建购物车列表Count = 0with open(BASE_DIR + 'goods_info.txt', 'r')as f:for line in f:goods_info.append(line.strip().split(''))with open(BASE_DIR + 'users_value.txt', 'r')as f:for line in f:if line.split('')[0] == Username:Salary = int(line.split('')[1])while True:for i, index in enumerate(goods_info):print(i, index)getNum = input("请输⼊要购买的商品编号,输⼊c结算,输⼊q退出:")if getNum.isdigit():#getNum=int(getNum)Count += int(goods_info[getNum][1])ShoopCar.append(goods_info[getNum][0])expense += int(goods_info[getNum][1])#消费⼊库if int(goods_info[getNum][2]) > 0:goods_info[getNum][2] = str(int(goods_info[getNum][2])-1)print("当前已消费 :\033[32;1m%s\033[0m"%Count)elif getNum=='c':#结算while True:opt = input("结算⽅式:1.余额,2.刷卡,3.退出 :")if opt.isdigit():if opt=='1':if Salary < Count:print("余额不⾜")passelse:print("付款成功,当前余额为:\033[32;1m%s\033[0m"%(Salary-Count))with open(BASE_DIR + 'users_info.txt', 'a')as f:f.write(Username + '' + ','.join(ShoopCar) + '' + str(expense) + '' + time.strftime('%Y-%m-%d-%X') + '\n') with open(BASE_DIR+'goods_info.txt', 'w')as f:for line in goods_info:f.write(''.join(line)+'\n')value_info = []with open(BASE_DIR+'users_value.txt', 'r')as f:for line in f:value_info.append(line.strip().split(''))for line in value_info:if line[0] == Username:line[1] = str(Salary-Count)with open(BASE_DIR + 'users_value.txt', 'w')as f:for line in value_info:f.write(''.join(line) + '\n')elif opt == '2':#刷卡if ATM_ExpensePort(Count)==True:#刷卡接⼝with open(BASE_DIR + 'ATM_UserInfo.txt', 'a')as f:f.write(Username + '' + ','.join(ShoopCar) + '' + str(expense) + '' + time.strftime('%Y-%m-%d-%X') + '\n') with open(BASE_DIR + 'users_info.txt', 'a')as f:f.write(Username + '' + ','.join(ShoopCar) + '' + str(expense) + '' + time.strftime('%Y-%m-%d-%X') + '\n') with open(BASE_DIR+'goods_info.txt', 'w')as f:for line in goods_info:f.write(''.join(line)+'\n')elif opt == '3':returnelse:passbreakelif getNum=='q':#退出breakelse:pass ATM.py程序代码如下:from ATMandShoopCar.ShoopingCar import DataAccessimport osBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+'/DataAccess/'#设置路径#ATM操作def ATM_Opt():a=[]with open(BASE_DIR+'ATM_UserCard.txt','r')as f:for line in f:a.append(line.strip().split(''))while True:opt = input("1.⽤户选项,2.管理员选项,输⼊q退出:")if opt.isdigit():if opt =='1':#⽤户选项while True:username=input("请输⼊⽤户账号,输⼊q退出:")if username=='q':breakpassword=input("请输⼊密码,输⼊q退出:")if password=='q':breakT = Falsefor line in a:if line[0]==username and line[1]==password:T = Trueprint("登⼊成功")while True:Chose =input("1.转账,2.提现,3.消费流⽔,4.还款,5.⽤户操作记录,输⼊q退出: ")DataAccess.ATM_UserTranster(username)#转账elif Chose=='2':DataAccess.ATM_UserWithdrawal(username)#提现elif Chose=='3':Username=input("请输⼊⽤户名:")DataAccess.ATM_UserWater(Username,username)#消费流⽔elif Chose=='4':DataAccess.ATM_UserReimbursement(username)#还款elif Chose=='5':DataAccess.ATM_UserOpt(username)#⽤户操作记录else:passelif Chose=='q':breakelse:passbreakif T ==False:print("账号密码错误!!")elif opt=='2':#管理员选项while True:Chose = input("1.添加账户,2.⽤户额度管理,3.账户冻结,输⼊q退出: ")if Chose.isdigit():if Chose == '1':DataAccess.ATM_UserAdd()#账户添加elif Chose =='2':DataAccess.Account_Manage()elif Chose =='3':er_freeze()else:passelif Chose =='q':global user_statususer_status = Falsebreakelse:passelse:passelif opt=='q':breakelse:pass ShoopingCar.py程序代码如下:from ATMandShoopCar.ShoopingCar import DataAccessdef ShoopingCar_Opt():while True:Num=input("1.⽤户界⾯,2.商家界⾯,输⼊q退出 :")if Num.isdigit():Num = int(Num)if Num == 1:username = input("Please Input The Username :")er_printAccountBalance(username)while True:UserChoose = input("1.查询购物记录,2.购物,3.充值,输⼊q返回上级⽬录 :") if UserChoose.isdigit():UserChoose = int(UserChoose)if UserChoose == 1:er_RecordsConsumption(username)#查询购物记录breakelif UserChoose == 2:er_ShoopCar(username)#购物车breakelif UserChoose == 3:value = int(input("请输⼊充值⾦额 :"))er_TopUp(username, value)#充值elif UserChoose=='q':breakelse:passelif Num == 2:#商家界⾯DataAccess.search_data_access()#打印商品信息和库存while True:UserChoose = input("1.添加商品,2.修改商品信息,3.删除商品,输⼊q返回上级⽬录 :") if UserChoose.isdigit():UserChoose = int(UserChoose)if UserChoose==1:goodsname=input("请输⼊商品名 :")goodsvalue=int(input("请输⼊商品价格 :"))goodnum = int(input("请输⼊商品数量 :"))DataAccess.add_goods_opt(goodsname, goodsvalue, goodnum)#商品添加操作elif UserChoose==2:goodsname = input("请输⼊要修改的商品名 :")goodsvalue = int(input("请输⼊商品价格 :"))goodnum = int(input("请输⼊商品数量 :"))DataAccess.Change_goods_info(goodsname, goodsvalue, goodnum)elif UserChoose==3:elif UserChoose=='q':breakelse:passelse:passelif Num == 'q':breakelse:pass main.py程序代码如下:from ATMandShoopCar.ShoopingCar import ShoopingCar from ATMandShoopCar.ShoopingCar import ATMdef main():while True:opt=input("1.ATM,2.购物车,输⼊q退出:") if opt.isdigit():if opt =='1':ATM.ATM_Opt()elif opt=='2':ShoopingCar.ShoopingCar_Opt()else:passelif opt=='q':breakelse:passmain() 数据库ATM_Use'rCard.txt格式如图: 数据库ATM_Use'rInfo.txt格式如图: 数据库ATM_UserOpt.txt格式如图: 数据库goods_info.txt格式如图: 数据库users_info.txt格式如图: 数据库users_value.txt格式如图:。
python多线程实现代码(模拟银⾏服务操作流程)1.模拟银⾏服务完成程序代码⽬前,在以银⾏营业⼤厅为代表的窗⼝⾏业中⼤量使⽤排队(叫号)系统,该系统完全模拟了⼈群排队全过程,通过取票进队、排队等待、叫号服务等功能,代替了⼈们站队的⾟苦。
排队叫号软件的具体操作流程为:顾客取服务序号当顾客抵达服务⼤厅时,前往放置在⼊⼝处旁的取号机,并按⼀下其上的相应服务按钮,取号机会⾃动打印出⼀张服务单。
单上显⽰服务号及该服务号前⾯正在等待服务的⼈数。
服务员⼯呼叫顾客服务员⼯只需按⼀下其柜台上呼叫器的相应按钮,则顾客的服务号就会按顺序的显⽰在显⽰屏上,并发出“叮咚”和相关语⾳信息,提⽰顾客前往该窗⼝办事。
当⼀位顾客办事完毕后,柜台服务员⼯只需按呼叫器相应键,即可⾃动呼叫下⼀位顾客。
编写程序模拟上⾯的⼯作过程,主要要求如下:程序运⾏后,当看到“请点击触摸屏获取号码:”的提⽰时,只要按回车键,即可显⽰“您的号码是:XXX,您前⾯有 YYY 位”的提⽰,其中XXX 是所获得的服务号码,YYY 是在 XXX 之前来到的正在等待服务的⼈数。
⽤多线程技术模拟服务窗⼝(可模拟多个),具有服务员呼叫顾客的⾏为,假设每个顾客服务的时间是10000ms,时间到后,显⽰“请 XXX 号到 ZZZ 号窗⼝!”的提⽰。
其中 ZZZ 是即将为客户服务的窗⼝号。
代码:以下为 python 实现:from Task04_Queue.linkedQueue import LinkedQueueimport threadingimport timeclass LinkBankQueue(LinkedQueue):def __init__(self):LinkedQueue.__init__(self)self.callNumber = 0def getCallNumber(self):if self.is_empty() and self.callNumber == 0:self.callNumber = 1else:self.callNumber += 1return self.callNumberdef getLength(self):if self.is_empty():return 0else:cur = self._headlen = 1while cur != self._tail:cur = cur.nextlen += 1return len# 服务器class ServiceWindow(threading.Thread):def __init__(self):threading.Thread.__init__(self)self.bankQueue = Noneself.lock = threading.Lock()def service(self):self.lock.acquire()while True:time.sleep(20)try:if not self.bankQueue.is_empty():print('请 %d 号到 %s 号窗⼝' % (self.bankQueue._head.data, threading.current_thread().name))self.bankQueue.dequeue()# time.sleep(10)else:print('队列为空哦')finally:self.lock.release()# 客户端if __name__ == '__main__':bankQueue = LinkBankQueue()windowcount = 2serviceWindows = [None] * windowcountthreadList = [None] * windowcountfor i in range(windowcount):serviceWindows[i] = ServiceWindow()serviceWindows[i].bankQueue = bankQueuethreadList[i] = threading.Thread(name=(i + 1), target=serviceWindows[i].service, args=())threadList[i].start()while True:input('请点击触摸屏获取号码:')callNumber = bankQueue.getCallNumber()if bankQueue != None:print('您的号码是:%d,您前⾯有 %d 位' % (callNumber, bankQueue.getLength()))bankQueue.enqueue(callNumber)else:print('您的号码是:%d,您前⾯有 0 位' % (callNumber))结果截图:总结以上所述是⼩编给⼤家介绍的python多线程实现代码(模拟银⾏服务操作流程),希望对⼤家有所帮助,如果⼤家有任何疑问请给我留⾔,⼩编会及时回复⼤家的。
任务名称:Python ATM机程序代码一、引言随着科技的不断发展,自动取款机(ATM)已经成为我们生活中不可或缺的一部分。
ATM机的出现方便了人们的日常生活,为我们提供了便捷的取款、转账和查询服务。
本文将详细介绍如何使用Python编写一个简单的ATM机程序代码,以实现基本的取款、存款和查询功能。
二、程序设计2.1 程序流程下面是程序的基本流程:1.用户输入账号和密码进行登录2.登录成功后,进入主菜单3.用户选择相应的功能进行操作:取款、存款、查询余额、退出4.用户执行完操作后,可以选择返回主菜单继续操作或退出程序2.2 导入模块首先,需要导入相应的模块,以便使用模块中的函数和方法。
在本程序中,我们需要使用time模块来添加延迟效果,以模拟实际的ATM机操作;使用getpass模块来隐藏用户输入的密码。
import timeimport getpass# 其他需要导入的模块(如数据库模块)可根据需要自行添加2.3 登录功能实现在ATM机中,用户需要先进行登录才能进行后续的操作。
因此,我们需要实现一个登录功能。
用户需要输入正确的账号和密码才能成功登录。
def login():account = input("请输入账号:")password = getpass.getpass("请输入密码:")# TODO: 进行账号密码验证的逻辑判断,可连接数据库查询用户信息# 模拟登录操作,延迟2秒time.sleep(2)print("登录成功!")2.4 主菜单功能实现登录成功后,用户将进入主菜单,可以选择相应的功能进行操作。
我们可以使用一个无限循环来实现,用户在每次操作完后,可以选择退出或继续操作。
def main_menu():while True:print("====== 主菜单 ======")print("1. 取款")print("2. 存款")print("3. 查询余额")print("4. 退出")choice = input("请输入您的选择:")if choice == "1":withdraw()elif choice == "2":deposit()elif choice == "3":check_balance()elif choice == "4":print("谢谢使用,再见!")breakelse:print("无效的选择,请重新输入!")2.5 取款、存款和查询余额功能实现在ATM机中,用户可以进行取款、存款和查询余额的操作。
Python编写ATM(初级进阶)Python3.7基于⾯向对象编程主要功能 ⼀. ⽤户功能 查询余额, 取款, 存款, 转账, 修改个⼈密码 ⼆. 管理员功能 添加新账号, 冻结账号, 解除冻结, 查询⽤户信息, 查询所有⽤户信息 三. 系统平台 登录, 冻结 四.其他 ⽂本存储, 信息格式位: 账号,密码,级别,⾦额,状态,如: X0001,1234,1,10000,0代码如下:1import os234# 普通⽤户5class Client:6def__init__(self, data):7print(data)8 self.id = data[0] # id9 self.password = data[1] # 密码10 self.level = data[2] # 级别11 self.money = data[3] # ⾦额12 self.stauts = data[4] # 状态1314# 查询⾦额15def chaxun(self):16print("账号'%s',余额为%.2f$" % (self.id, int(self.money)))17return self.money1819# 取钱20def qu(self):21 num = int(input("输⼊取⾛⾦额(以百为单位,最⾼5000):"))22while num % 100 != 0 or num > int(self.money) or num < 100 or num > 5000:23 num = int(input("输⼊错误,请重试:"))24 data_list = []25 with open("user_info.txt", 'r', encoding='utf8') as f:26for line in f:27 data_list.append(line)28 with open("user_info(副本).txt", 'w', encoding='utf8') as f1:29for i in range(len(data_list)):30 detail_list = data_list[i].strip().split(',')31if detail_list[0] == self.id:32# 取完后的钱33 self.money = str(int(detail_list[3]) - num)34 detail_list[3] = self.money35 info_str = ','.join(detail_list) + "\n"36 f1.write(info_str)37else:38 info_str = ','.join(detail_list) + '\n'39 f1.write(info_str)40 os.remove('user_info.txt')41 os.rename('user_info(副本).txt', 'user_info.txt')42print("账号'%s',取⾛%.2f$,余额为%.2f$" % (self.id, int(num), int(self.money)))43return self.money44# 存钱45def cun(self):46 num = int(input("输⼊存⼊⾦额(以百为单位):"))47while num % 100 != 0 or num < 100:48 num = int(input("输⼊错误,请重试:"))49 data_list = []50 with open("user_info.txt", 'r', encoding='utf8') as f:51for line in f:52 data_list.append(line)53 with open("user_info(副本).txt", 'w', encoding='utf8') as f1:54for i in range(len(data_list)):55 detail_list = data_list[i].strip().split(',')56if detail_list[0] == self.id:57# 存完之后的钱58 self.money = str(int(detail_list[3]) + num)59 detail_list[3] = self.money60 info_str = ','.join(detail_list) + "\n"61 f1.write(info_str)62else:63 info_str = ','.join(detail_list) + '\n'64 f1.write(info_str)65 os.remove('user_info.txt')66 os.rename('user_info(副本).txt', 'user_info.txt')67print("账号'%s',取⾛%.2f$,余额为%.2f$" % (self.id, int(num), int(self.money))) 68return self.money6970# 转账71def zhuan(self):72 id_list = []73 with open("user_info.txt", 'r', encoding='utf8') as f:74for line in f:75 info_list = line.strip().split(',')76 id_list.append(info_list[0])77print("#ID列表", id_list, )78 id = input("输⼊转账ID:")79while id not in id_list or id == self.id:80 id = input("ID输⼊错误,请重试:")81if id.lower() == 'q':82return8384 num = int(input("输⼊转账⾦额(以百为单位,最⾼5000):"))85while num % 100 != 0 or num > int(self.money) or num < 100 or num > 5000: 86 num = int(input("⾦额输⼊错误,请重试:"))8788 data_list = []89 with open("user_info.txt", 'r', encoding='utf8') as f:90for line in f:91 data_list.append(line)9293 with open("user_info(副本).txt", 'w', encoding='utf8') as f1:94for i in range(len(data_list)):95 detail_list = data_list[i].strip().split(',')96if detail_list[0] == self.id: # 修改⾃⼰的⾦额97 self.money = str(int(detail_list[3]) - num)98 detail_list[3] = self.money99 info_str = ','.join(detail_list) + "\n"100 f1.write(info_str)101elif detail_list[0] == id: # 增加接收⼈的⾦额102 detail_list[3] = str(int(detail_list[3]) + num)103 info_str = ','.join(detail_list) + "\n"104 f1.write(info_str)105else:106 info_str = ','.join(detail_list) + '\n'107 f1.write(info_str)108 os.remove('user_info.txt')109 os.rename('user_info(副本).txt', 'user_info.txt')110print("转账成功,剩余余额%.2f" % int(self.money))111return self.money112113# 修改密码114def xiugai(self, ):115 old_pwd = input("输⼊旧密码:")116while old_pwd != self.password:117 old_pwd = input("密码错误,请重试:")118119 new_pwd = input("输⼊新密码(q返回):")120if new_pwd.lower() == 'q':121print("取消修改密码")122return123124while len(new_pwd) < 6 or len(set(new_pwd)) == 1:125 new_pwd = input("新密码不能⼩于6位或者6位完全相同,请重试:")126127 new_pwd_2 = input("确认新密码:")128while len(new_pwd_2) < 6 or len(set(new_pwd_2)) == 1:129print("新密码不能⼩于6位或者6位完全相同,请重试:")130if new_pwd == new_pwd_2:131 data_list = []132 with open("user_info.txt", 'r', encoding='utf8') as f:133for line in f:134 data_list.append(line)135136 with open("user_info(副本).txt", 'w', encoding='utf8') as f1:137for i in range(len(data_list)):138 detail_list = data_list[i].strip().split(',')139if detail_list[0] == self.id: # 修改⾃⼰密码140 self.password = new_pwd141 detail_list[1] = self.password142 info_str = ','.join(detail_list) + "\n"143 f1.write(info_str)144else:145 info_str = ','.join(detail_list) + '\n'146 f1.write(info_str)147 os.remove('user_info.txt')148 os.rename('user_info(副本).txt', 'user_info.txt')149print("密码修改成功,新密码为%s" % self.password)150return self.password151152else:153print("2次密码不⼀样,请重试")154return155156# 管理员157class Admin:158def__init__(self):159 self.id = 'a0001'160 self.password = '112233'161162# 添加⽤户163def tianjia(self):164 id_list = []165 with open("user_info.txt", 'r', encoding='utf8') as f:166for line in f:167 info_list = line.strip().split(',')168 id_list.append(info_list[0])169170 new_id = input("输⼊新账号ID:")171while new_id in id_list:172 new_id = input("ID已存在,请重试:")173174 with open("user_info.txt", 'a', encoding='utf8') as f:175 f.write(new_id + ',' + '123456' + ',' + '1' + ',' + '10000' + ',' + '0' + '\n') 176print(new_id, '添加成功')177178# 冻结179def dongjie(self):180 id_list = []181 with open("user_info.txt", 'r', encoding='utf8') as f:182for line in f:183 info_list = line.strip().split(',')184 id_list.append(info_list[0])185186 dongjie_id = input("输⼊冻结账号ID:")187while dongjie_id not in id_list:188 dongjie_id = input("ID不存在,请重试:")189190 data_list = []191 with open("user_info.txt", 'r', encoding='utf8') as f:192for line in f:193 data_list.append(line)194195 with open("user_info(副本).txt", 'w', encoding='utf8') as f1:196for i in range(len(data_list)):197 detail_list = data_list[i].strip().split(',')198if detail_list[0] == dongjie_id: # 修改⾃⼰密码199 detail_list[-1] = '1'200 info_str = ','.join(detail_list) + "\n"201 f1.write(info_str)202else:203 info_str = ','.join(detail_list) + '\n'204 f1.write(info_str)205 os.remove('user_info.txt')206 os.rename('user_info(副本).txt', 'user_info.txt')207print(dongjie_id, '以冻结')208209# 解冻210def jiedong(self):211 id_list = []212 with open("user_info.txt", 'r', encoding='utf8') as f:213for line in f:214 info_list = line.strip().split(',')215 id_list.append(info_list[0])216217 jiedong_id = input("输⼊解冻账号ID:")218while jiedong_id not in id_list:219 jiedong_id = input("ID不存在,请重试:")220221 data_list = []222 with open("user_info.txt", 'r', encoding='utf8') as f:223for line in f:224 data_list.append(line)225226 with open("user_info(副本).txt", 'w', encoding='utf8') as f1:227for i in range(len(data_list)):228 detail_list = data_list[i].strip().split(',')229if detail_list[0] == jiedong_id: # 修改⾃⼰密码230 detail_list[-1] = '0'231 info_str = ','.join(detail_list) + "\n"232 f1.write(info_str)233else:234 info_str = ','.join(detail_list) + '\n'235 f1.write(info_str)236 os.remove('user_info.txt')237 os.rename('user_info(副本).txt', 'user_info.txt')238print(jiedong_id, '已解冻')239240# 查询⽤户信息241def chaxun(self):242 id_list = []243 with open("user_info.txt", 'r', encoding='utf8') as f:244for line in f:245 info_list = line.strip().split(',')246 id_list.append(info_list[0])247print('ID列表', id_list)248 chaxun_id = input("查询ID:")249250while chaxun_id not in id_list:251print('ID列表', id_list)252 chaxun_id = input("ID不存在,请重试:")253254 l = ['账号', '密码', '级别(0管理员,1普通)', '⾦额', '状态(0正常,1冻结)'] 255256 with open("user_info.txt", 'r', encoding='utf8') as f:257for line in f:258 info_list = line.strip().split(',')259if chaxun_id == info_list[0]:260for i in range(len(info_list)):261print(l[i], ">>>", info_list[i])262return263else:264print("ID不存在,请重试:")265266267# ATM 系统268class ATM:269270def__init__(self):271 with open("user_info.txt", 'w', encoding='utf8') as f:272 f.write("a0001,112233,0,10000,0" + '\n') # 管理员273 f.write("p0001,123456,0,10000,0" + '\n') # 普通账号1274 f.write("p0002,123456,0,10000,0" + '\n') # 普通账号2275276# 密码错三次冻结277def dongjie(self, ID):278 data_list = []279 with open("user_info.txt", 'r', encoding='utf8') as f:280for line in f:281 data_list.append(line)282283 with open("user_info(副本).txt", 'w', encoding='utf8') as f1:284for i in range(len(data_list)):285 detail_list = data_list[i].strip().split(',')286if detail_list[0] == ID: # 修改⾃⼰密码287 detail_list[-1] = '1'288 info_str = ','.join(detail_list) + "\n"289 f1.write(info_str)290else:291 info_str = ','.join(detail_list) + '\n'292 f1.write(info_str)293 os.remove('user_info.txt')294 os.rename('user_info(副本).txt', 'user_info.txt')295296# z主程序运⾏297def run(self):298 ID = input("请输⼊卡号:")299 password = input("请输⼊密码:")300 client = None301 admin = None302303# 管理员登录304if ID == 'a0001':305while password != '112233':306 password = input("密码错误,联系管理员(q退出系统):")307if password.lower() == 'q':308print('退出系统...')309return310print("管理员登录成功")311 admin = Admin()312313if admin != None:314 task = {'1': admin.tianjia, '2': admin.dongjie, '3': admin.jiedong, '4': admin.chaxun}315 menu = {'1': "添加账号", '2': "冻结账号", '3': "解冻", '4': "查询信息", '5': '退出系统'}316317while 1:318for k, v in menu.items():319print(k, v)320321 choice = input("请输⼊你要执⾏的任务序号:")322if choice == '5':323print('退出系统...')324return325try:326 task[choice]()327except Exception as e:328print("出错,请重试....")329print('\n')330331 with open("user_info.txt", 'r', encoding='utf8') as f:332 data_list = []333for line in f:334 data_list.append(line)335336for line in data_list:337 num = 1338339# ⽤户信息列表340 data = line.strip().split(",")341if ID == data[0]: # 判断账号是否存在342if data[-1] == "1":343print('该账号已冻结,请联系管理员解冻')344return345346# 密码错三次账号冻结347while password != data[1] and num < 3:348 num += 1349 password = input("密码错误,请重试(第%s次尝试):" % num)350351if ID == data[0] and password == data[1]:352353print('"%s",登录成功\n' % ID)354 client = Client(data) # 实例化⼀个客户类把⽤户信息传进去355break# 跳出 for 循环356357else:358 self.dongjie(ID)359print("该账号'%s'已冻结,联系管理员解冻" % ID)360break# 跳出 for 循环361else:362print("账号'%s'不存在,请联系管理员" % ID)363364if client != None:365 task = {'1': client.chaxun, '2': client.qu, '3': client.cun, '4': client.zhuan, '5': client.xiugai} 366 menu = {'1': "查询余额", '2': "取款", '3': "存款", '4': "转账", '5': "修改个⼈密码", '6': '退出系统'} 367while 1:368for k, v in menu.items():369print(k, v)370371 choice = input("请输⼊你要执⾏的任务序号(默认为1):")372if choice == '6':373print('退出系统...')374return375try:376 task[choice]()377except Exception as e:378print("出错,请重试...")379print('\n')380381382if__name__ == '__main__':383 ATM().run() # 程序的⼊⼝。
第2次综合训练报告题目:银行ATM模拟程序姓名:张也白专业:安全工程班级:通风15-1班指导教师:邓立军2016 年 5 月9 日目录1 摘要 (1)2.设计思路 (1)3.源程序 (6)4.代码分析 (2)参考资料 (3)银行ATM模拟程序1 摘要自动柜员机,即ATM,是指银行在不同地点设置一种小型机器,利用一张信用卡大小的胶卡上的磁带记录客户的基本户口资料(通常就是银行卡),让客户可以透过机器进行提款、存款、转账等银行柜台服务,大多数客户都把这种自助机器称为自动提款机。
本文正是通过设计一个ATM模拟模拟程序来实现ATM机系统的基本功能,充分运用自己所学的Python知识进行设计编程。
实现的主要功能有:账户信息查询、存款操作、取款操作、修改密码功能、退出系统功能。
用户任意选择1张银行卡(输入1位1~3的数字),输入初始密码123456即可进入ATM操作系统菜单(如图1所示),若输入密码连续错误三次则锁卡自动退出系统(如图2所示),系统菜单各功能(如图3所示)。
编写程序时的环境是Python3.4,所以代码中print及input函数可能与python2.X版本有一些差别。
参考了教材中第八章面向对象程序设计,编写了两个类包括ATM机类和银行卡Card 类,编写了若干个函数以实现整个程序模拟ATM机的各种功能。
变量和函数的命名主要使用了Camel命名法,类的命名主要使用了Pascal命名法,程序共189行(含空行),因为时间比较仓促,可能有些地方写的比较乱,有些地方命名也不规范。
另外因为对文件的操作不熟练,在网上也没找到太多相关的资料,请多包涵。
图1图2图32设计思路程序设计灵感来自银行ATM机,在这里将ATM机的各种功能抽象与简化,设计了银行ATM 模拟程序。
根据我们日常的生活经验,我们要使用ATM机就需要一张银行卡。
运用面向对象的编程方法,把ATM机和银行卡简化并抽象为两个类:1)银行卡类,主要用来存储账户信息,包括卡号、密码、用户名、余额四个属性,另外写了一个构造方法。
2)ATM机类,主要用来查询和修改银行卡的信息,写了五个方法,以银行卡类的对象作为参数,实现银行卡查询(包括卡号、密码、用户名、余额)、存款(银行卡余额增加)、取款(银行卡余额减少)、修改银行卡密码、退卡(退出程序)等功能。
写好了类后,我们开始模拟ATM机的操作过程。
首先,使用ATM机我们需要插卡,从文件中读取银行卡信息(想法并没有能很好的实现),我们预设三张银行卡,用户选择(1~3号银行卡),根据银行卡信息创建一个对应的银行卡对象,以及ATM机对象。
插卡后,我们需要用户输入密码。
如果输入密码与银行卡密码匹配就进入ATM系统,如果输入密码错误打到三次就锁卡退出。
进入ATM系统,用户可以选择ATM的五个功能:1)银行卡查询,实现的方法就是使用print函数输出银行卡的卡号、密码、用户名、余额。
2)存款,实现的方法就是把银行卡的余额+X×100,(X为正整数),约束条件为存款金额大于100小于10000。
3)取款,实现的方法就是把银行卡的余额-X×100,(X为正整数),约束条件为取款金额不大于存款金额且不大于5000。
4)密码修改,实现的方法就是把银行卡的密码修改。
首先要输入原密码,如果原密码输入错误,则修改密码失败,成功后需要用户输入新密码两次,如果两次密码一致则修改成功,否则密码修改失败。
5)退卡,使用exit()函数退出程序3 源程序1. #!/usr/bin/python2. # -*- coding: utf-8 -*-3. #author:张也白 PythonVersion:3.44. import os5.6. class DepositCard:7. cardID = 08. cardPWD = '123456'9. balance = 010. userName = '0000'11. def __init__(self,cardID,cardPWD,userName,balance):12. self.cardID = cardID13. self.cardPWD = cardPWD14. erName = userName15. self.balance = balance16.17. class ATM:18. def deposite(self,card):#存款19. divide()20. info = "存款\n"21. print(info.center(50))22. cash=input("提示:存款金额为100的倍数,金额要求在100-10000之间\n")23. if int(cash)%100==0 and int(cash)>0 and int(cash)<=10000:24. card.balance+=int(cash)25. info = "存款成功\n"26. print(info.center(50))27. print("\nThe balance of the card :%d"%card.balance)28. else:29. info = "存款失败\n"30. print(info.center(50))31. divide()32.33. def withdraw(self,card):#取款34. divide()35. info = "取款\n"36. print(info.center(50))37. options={1:'100',2:'200',3:'500',4:'其他金额'}38. for a in options.items():39. print(a[0],a[1])40. choice=input('请选择:')41. if (int(choice)==1 or int(choice)==2) and card.balance>=int(choice)*100:42.43. card.balance-=int(choice)*10044. info = "取款成功\n"45. print(info.center(50))46. elif int(choice)==3 and card.balance>=500:47. card.balance-=50048. info = "取款成功\n"49. print(info.center(50))50. elif int(choice)==4:51. cash=input("\n提示:取款金额为100的倍数,且总额不超过5000元\n请52.输入你要取的金额:")53. if int(cash)>=100 and int(cash)<=5000:54. if int(cash)%100==0 and card.balance>=int(cash):55. card.balance-=int(cash)56. info = "取款成功\n"57. print(info.center(50))58. else:59. print('输入错误或卡内余额不足')60. else:61. print('输入错误或卡内余额不足')62. else:63. print('输入错误或卡内余额不足')64.65.66. print("\n\nThe balance of the card :%d"%card.balance)67. divide()68.69. def modify(self,card):#修改密码70. divide()71. info = "修改密码\n"72. print(info.center(50))73. inStr=input('请输入原密码:')74. if inStr!=card.cardPWD:75. info = "密码错误\n"76. print(info.center(50))77. else:78. newPWD1=input('请输入新密码:')79. newPWD2=input('请再次输入新密码:')80. if newPWD1 == newPWD2:81. card.cardPWD=newPWD182. info = "\n密码修改成功,请牢记你的新密码\n"83. print(info.center(50))84. else:85. info = "\n密码不一致\n"86. print(info.center(50))87. divide()88.89. def query(self,card):#查询90. divide()91. info = "查询成功\n"92. print(info.center(50))93. print('银行卡信息'.center(50))94. print('%-10s%-10s%-10s%-10s'%('卡号','密码','姓名','余额'))95.print('%-11s%-11s%-11s%-11s'%(str(card.cardID),card.cardPWD,erNam96. e,str(card.balance)))97. divide()98. def refundCard(self,card):#退卡99. divide()100. print('(假装把卡吐出来)')101. print('谢谢使用,请收好您的卡片')102. divide()103. def divide():104. print("\n--------------------------------------------------\n") 105. def init():106. f=open('D:\\a.txt','w')107. info='''\108. 1001 123456 张大白 1000109. 1002 123456 张二白 2000110. 1003 123456 张三白 3000'''111. f.write(info)112. f.close()113. s=open('D:\\a.txt','r')114. print('银行卡信息'.center(50))115. print('%-10s%-10s%-10s%-10s'%('卡号','密码','姓名','余额')) 116. for line in s.readlines():117. for i in range(0,4):118. print('%-11s'%line.split()[i],end ='')119. if i==3:120. print()121. s.close122. divide()123. return124. def createCard():125. choice=input('请选择一张银行卡(1~3):');126. if int(choice) == 1:127. newcard = DepositCard(1001,'123456','张大白',1000) 128. login(newcard)129. elif int(choice) == 2:130. newcard = DepositCard(1002,'123456','张二白',2000) 131. login(newcard)132. elif int(choice) == 3:133. newcard = DepositCard(1003,'123456','张三白',3000) 134. login(newcard)135. else:136. print('输入有误,退出系统')137. exit()138. def login(card):139. divide()140. print('\n 你插入了银行卡%s\n'%card.cardID) 141. sum = 0142. pwd = ''143. while pwd!=card.cardPWD:144. pwd=input('\n请输入密码:')145. sum+=1146. if pwd == card.cardPWD:147. break148. else:149. print('密码错误次数%d,请重新输入密码'%sum) 150. if sum > 2:151. print('\n密码错误次数过多,退出系统') 152. exit()153. print('\n密码正确,进入系统')154. divide()155. XiaoBaiATM = ATM()156. menu(XiaoBaiATM,card)157. def start():158. divide()159. print("\t\t欢迎使用小白白ATM")160. divide()161. init()162. createCard()163. def menu(XiaoBaiATM,card):164. options={1:'查询账户信息',2:'存款',3:'取款',4:'修改密码',5:'退卡'} 165. for a in options.items():166. print(a[0],a[1])167. choice = input('\n请选择:')168. if int(choice) == 1:169. XiaoBaiATM.query(card)170. menu(XiaoBaiATM,card)171. elif int(choice) == 2:172. XiaoBaiATM.deposite(card)173. menu(XiaoBaiATM,card)174. elif int(choice) == 3:175. XiaoBaiATM.withdraw(card)176. menu(XiaoBaiATM,card)177. elif int(choice) == 4:178. XiaoBaiATM.modify(card)179. menu(XiaoBaiATM,card)180. elif int(choice) == 5:181. XiaoBaiATM.refundCard(card)182. else:183. print('输入有误')184. menu(XiaoBaiATM,card)185. print()186. def main():187. start()188. if __name__ == "__main__":189. main()4代码分析首先执行第X行,进行输入。