Python银行程序存取款后循环要求输入用户名问题排查
问题概述
- 开发基于Python的银行账户管理系统,技术栈包含SQLite,后续计划接入Tkinter实现GUI交互
- 当前进度:第一阶段单用户文件I/O模块开发中,已实现余额读取、账户创建、登录、存款、取款、余额查询基础逻辑;第二阶段数据库模块未完成
- 故障现象:存款或取款操作执行完成后,程序未停留在结果展示页面,反而回到初始流程要求输入用户名,出现非预期的流程跳转
问题复现代码
# PHASE 1 (FILE I/O with One Customer) # Initialization of Current Balance ** Current Balance is the same for all users for the sake of simplicity ** myMoney = open("current_balance.txt") currentBalance = int(myMoney.readline()) # Imports import sqlite3 # Creation of Bank Account and Notifying User(s) of Current Balance class Bank_Account: def __init__(self): self.balance= currentBalance print("Welcome to Your Bank Account System!") # If statements for first screen def options_1(self): ch = int(input("1. Create an Account\n2. Log into Your Account\nEnter a Choice: ")) if ch == 1: self.create() if ch == 2: self.Log_in() def options_2(self): ch= int(input("1. Withdraw Money from Your Account\n2. Deposit Money to Your Account\nEnter a Choice: ")) if ch == 1: self.withdraw() if ch == 2: self.deposit() # Function to Create an Account def create(self): user_create = str(input("Enter a Username:")) pin_create = int(input("Enter a Pin Number:" )) print("Account successfully created!") # Function to Log into Account def Log_in(self): user = str(input("Enter your username:")) pin = int(input("Enter your Pin Number:")) print("Welcome", user, "!") # Function to Deposit Money def deposit(self): amount=float(input("Enter the amount you want to deposit: ")) self.balance += amount print("Amount Deposited: ",amount) print("Net Available Balance=",self.balance) # Function to Withdraw Money def withdraw(self): amount = float(input("Enter the amount you want to withdraw: ")) if self.balance>=amount: self.balance-=amount print("You withdrew: ",amount) print("Net Available Balance=",self.balance) else: print("Insufficient balance ") def display(self): print("Net Available Balance=",self.balance) # Creating an object of class self = Bank_Account() # Calling functions with that class self.options_1() self.options_2() self.create() self.display() # PHASE 2 (With Database) # Define Connection and Cursor connection = sqlite3.connect('Bank_Users.db') cursor = connection.cursor() # Create Users Table command1 = """ CREATE TABLE IF NOT EXISTS bank(pin INTEGER PRIMARY KEY, username TEXT)""" cursor.execute(command1) # Add to Users/Bank cursor.execute("INSERT INTO bank VALUES (7620, 'Kailas Kurup')") cursor.execute("INSERT INTO bank VALUES (4638, 'Bethany Watkins')") cursor.execute("INSERT INTO bank VALUES (3482, 'John Hammond')") cursor.execute("INSERT INTO bank VALUES (3493, 'Melissa Rodriguez')") cursor.execute("INSERT INTO bank VALUES (9891, 'Gopalakrishnan Nair')") # Get Results cursor.execute("SELECT * FROM bank") results = cursor.fetchall() print(results)
故障原因
核心问题是主流程调用逻辑顺序错误,不存在所谓的全局循环:
- 实例化类之后,代码按硬编码顺序线性执行:
options_1()(创建/登录菜单)→options_2()(存取款菜单)→create()(创建账户,第一行就是要求输入用户名的input逻辑)→display() - 存取款操作在
options_2()里执行完成后,代码会直接运行下一行的self.create(),自然会弹出输入用户名的提示,和循环逻辑无关。
除此之外代码还存在几个明显缺陷:
- 打开
current_balance.txt读取余额后没有关闭文件句柄,会造成资源泄漏 - 将类实例命名为
self,违反Python命名约定:self是类实例方法中用于指代当前实例的固定参数名,全局使用会造成语义混淆 - 存取款操作仅修改内存中的余额变量,没有将更新后的余额写回
current_balance.txt,程序重启后余额会重置为初始值 - Phase2的SQLite逻辑存在问题:每次运行都会重复插入5条固定测试数据,而
pin是主键,第二次运行就会触发唯一约束报错;数据库操作完成后没有执行commit()提交事务,也没有关闭连接 - 登录、创建账户逻辑没有任何校验,输入任意用户名、PIN都能直接通过,也没有持久化存储用户信息
第一阶段核心问题修复方案
只需要删除主流程中多余的self.create()调用,即可解决存取款后要求输入用户名的问题,对应修复点如下:
- 调整
Bank_Account初始化方法,通过参数传入初始余额,不依赖全局变量
def __init__(self, init_balance): self.balance = init_balance print("Welcome to Your Bank Account System!")
- 修正主流程逻辑,规范实例命名,补全文件读写关闭、余额持久化逻辑,临时注释会报错的重复数据库插入代码
if __name__ == "__main__": # 读取初始余额,with语法会自动关闭文件 with open("current_balance.txt", "r") as f: currentBalance = int(f.readline()) # 不要用self作为全局实例名 account = Bank_Account(currentBalance) account.options_1() account.options_2() account.display() # 将更新后的余额写回文件,避免重启丢失 with open("current_balance.txt", "w") as f: f.write(str(account.balance)) # 数据库测试逻辑,测试数据插入仅首次运行执行,后续注释避免主键冲突 # connection = sqlite3.connect('Bank_Users.db') # cursor = connection.cursor() # command1 = """ CREATE TABLE IF NOT EXISTS bank(pin INTEGER PRIMARY KEY, username TEXT)""" # cursor.execute(command1) # # 首次建表时执行插入,后续注释 # # cursor.execute("INSERT INTO bank VALUES (7620, 'Kailas Kurup')") # # cursor.execute("INSERT INTO bank VALUES (4638, 'Bethany Watkins')") # # cursor.execute("INSERT INTO bank VALUES (3482, 'John Hammond')") # # cursor.execute("INSERT INTO bank VALUES (3493, 'Melissa Rodriguez')") # # cursor.execute("INSERT INTO bank VALUES (9891, 'Gopalakrishnan Nair')") # cursor.execute("SELECT * FROM bank") # results = cursor.fetchall() # print(results) # connection.commit() # connection.close()
内容的提问来源于stack exchange,提问作者kkurup
相关产品推荐
相关产品推荐

