You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何永久修改变量?ATM程序PIN码修改失效求助

ATM模拟程序PIN码不生效问题解决及代码优化

问题根源

每次调用atm_machine()函数时,real_pin_code和balance都会被重新初始化为4137和10000。你修改的real_pin_code只是当前函数调用中的局部变量,函数执行结束后就会被销毁,下次调用函数时又会回到初始值,所以PIN码变更无法持久。

解决方案

方案1:使用全局变量(新手友好)

将real_pin_code和balance定义为全局变量,在函数内部通过global关键字声明,确保修改的是全局作用域的变量,这样变更后的值会被保留。

方案2:使用类封装状态(规范写法)

把ATM的核心状态(PIN码、余额)和操作逻辑封装成类,通过实例对象保存状态,避免全局变量的弊端,代码结构更清晰。

优化后的代码示例

方案1(全局变量实现)

# 全局变量保存状态
real_pin_code = 4137
balance = 10000

def atm_machine():
    global real_pin_code, balance
    try:
        pin_code = int(input("Enter your PIN code:"))
    except ValueError:
        print("PIN码必须是数字!")
        print("Wait for your card!")
        return
    
    if pin_code == real_pin_code:
        print("""
          ATM   
    1)Check Balance
    2)Add money
    3)Extract money
    4)Change PIN code\n""")
        try:
            number_select = int(input("Select a number:"))
        except ValueError:
            print("请输入1-4之间的数字!")
            atm_recall()
            return
        
        if number_select < 1 or number_select > 4:
            print("You must select a number between 1 and 4!")
            atm_recall()
            return
        
        if number_select == 1:
            print(f"Your current balance is: {balance} $")
            atm_recall()
        
        elif number_select == 2:
            try:
                money_add = int(input("Enter amount of money you want to add:"))
                if money_add <= 0:
                    print("存款金额必须大于0!")
                    atm_recall()
                    return
            except ValueError:
                print("请输入有效的金额数字!")
                atm_recall()
                return
            balance += money_add
            print(f"Your current balance is: {balance} $")
            atm_recall()
        
        elif number_select == 3:
            try:
                money_extract = int(input("Enter the amount of money you want to extract:"))
                if money_extract <= 0:
                    print("取款金额必须大于0!")
                    atm_recall()
                    return
            except ValueError:
                print("请输入有效的金额数字!")
                atm_recall()
                return
            
            if money_extract > balance:
                print("Insufficient fund")
                atm_recall()
            else:
                balance -= money_extract
                print(f"Your current balance is: {balance} $")
                atm_recall()
        
        elif number_select == 4: 
            measure_pin = 9999
            try:
                changed_pin_code = int(input("Enter new PIN code:"))
            except ValueError:
                print("PIN码必须是数字!")
                print("Wait for your card")
                atm_recall()
                return
            
            if changed_pin_code == real_pin_code:
                print("You can't enter the same PIN code!")
                print("Wait for your card!")
                atm_recall()
            elif changed_pin_code > measure_pin or changed_pin_code < 1000:
                print("PIN code must be formed of 4 digits!")
                print("Wait for your card")
                atm_recall()
            else:
                real_pin_code = changed_pin_code
                print("PIN code successfully changed!")
                print(f"Your new PIN code is: {changed_pin_code}")
                atm_recall()
    
    else:
        print("PIN code incorrect!")
        print("Wait for your card!")

def atm_recall():
    while True:
        question = input('To make another action, type "Y", else, type "N" ').strip().upper()
        if question == "Y":
            atm_machine()
            break
        elif question == "N":
            print("Good Bye!")
            print("Wait for your card!")
            break
        else:
            print("请输入Y或N!")

atm_machine()

方案2(类封装实现)

class ATMMachine:
    def __init__(self):
        self.real_pin_code = 4137
        self.balance = 10000

    def show_menu(self):
        print("""
          ATM   
    1)Check Balance
    2)Add money
    3)Extract money
    4)Change PIN code\n""")

    def validate_pin(self):
        try:
            pin_code = int(input("Enter your PIN code:"))
            return pin_code == self.real_pin_code
        except ValueError:
            print("PIN码必须是数字!")
            print("Wait for your card!")
            return False

    def check_balance(self):
        print(f"Your current balance is: {self.balance} $")

    def add_money(self):
        try:
            money_add = int(input("Enter amount of money you want to add:"))
            if money_add <= 0:
                print("存款金额必须大于0!")
                return
            self.balance += money_add
            print(f"Your current balance is: {self.balance} $")
        except ValueError:
            print("请输入有效的金额数字!")

    def extract_money(self):
        try:
            money_extract = int(input("Enter the amount of money you want to extract:"))
            if money_extract <= 0:
                print("取款金额必须大于0!")
                return
            if money_extract > self.balance:
                print("Insufficient fund")
            else:
                self.balance -= money_extract
                print(f"Your current balance is: {self.balance} $")
        except ValueError:
            print("请输入有效的金额数字!")

    def change_pin(self):
        measure_pin = 9999
        try:
            changed_pin_code = int(input("Enter new PIN code:"))
            if changed_pin_code == self.real_pin_code:
                print("You can't enter the same PIN code!")
                print("Wait for your card!")
            elif changed_pin_code > measure_pin or changed_pin_code < 1000:
                print("PIN code must be formed of 4 digits!")
                print("Wait for your card")
            else:
                self.real_pin_code = changed_pin_code
                print("PIN code successfully changed!")
                print(f"Your new PIN code is: {changed_pin_code}")
        except ValueError:
            print("PIN码必须是数字!")
            print("Wait for your card")

    def run(self):
        while True:
            if not self.validate_pin():
                break
            self.show_menu()
            try:
                number_select = int(input("Select a number:"))
                if number_select < 1 or number_select > 4:
                    print("You must select a number between 1 and 4!")
                    continue
            except ValueError:
                print("请输入1-4之间的数字!")
                continue

            if number_select == 1:
                self.check_balance()
            elif number_select == 2:
                self.add_money()
            elif number_select == 3:
                self.extract_money()
            elif number_select == 4:
                self.change_pin()

            while True:
                question = input('To make another action, type "Y", else, type "N" ').strip().upper()
                if question == "Y":
                    break
                elif question == "N":
                    print("Good Bye!")
                    print("Wait for your card!")
                    return
                else:
                    print("请输入Y或N!")

if __name__ == "__main__":
    atm = ATMMachine()
    atm.run()

代码优化建议

  • 替换递归为循环:原代码用递归调用atm_machine()实现重复操作,多次调用会触发Python递归深度限制,改用循环更安全稳定。
  • 完善输入验证:新增对非数字输入、无效金额(≤0)、无效操作选项的验证,避免程序崩溃。
  • 优化条件逻辑:用elif替代多个独立if,减少不必要的条件判断;修正原代码中操作选项的错误判断逻辑(number_select >4 and number_select==0改为number_select <1 or number_select>4)。
  • 修复状态持久化问题:原存款功能未更新balance变量,优化后确保余额和PIN码的修改能被持久保存。
  • 修正拼写错误:统一修正Insufficent→Insufficient、succesfully→successfully等拼写错误。
  • 简化重复逻辑:将重复的提示信息、输入验证逻辑封装成函数或类方法,减少代码冗余,提升可读性。

内容的提问来源于stack exchange,提问作者Vasi Stirbu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 21:50:39