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

Python运行报错IndexError: tuple index out of range求根源分析

问题诊断与修复方案

直接报错原因

你遇到的IndexError: tuple index out of range错误由字符串格式化语法错误直接触发:
在main.py第4行的amongus = str.format("Starting Balance: {:.2f}")代码中,模板字符串里有1个占位符{:.2f},但你没有传入对应的填充参数,format方法找不到对应位置的填充值就抛出了索引越界错误。
相同的问题也存在于Bank.py的deposit、withdraw方法中,两处str.format调用都写了占位符但没有传入对应的amount参数。
修复方式:给format方法传入对应的填充值即可,main.py对应行修改为:

amongus = "Starting Balance: {:.2f}".format(balance)

Bank.py中对应行分别修改为:

# deposit方法内
amongus = "Depositing {:.2f}".format(amount)
# withdraw方法内
amongus = "Withdrawing {:.2f}".format(amount)

其余需要修复的代码问题

修正上述错误后你还会遇到其他报错,按如下规则修改即可:

  • Input模块调用错误:你定义的Validator类没有构造方法,不能直接实例化,应该调用类下封装的get_float静态方法获取输入的金额,main.py对应行修改为:
    amount = Input.Validator.get_float("Please enter deposit amount ($0.00 - $1000.00): ", 0.00, 1000.00)
    
  • Bank模块的ATM类逻辑错误:
    1. 三个方法没有声明为静态方法,直接调用会触发参数不匹配错误,给每个方法上方加上@staticmethod装饰器即可
    2. 方法内部需要修改Bank模块的全局balance变量,必须在修改变量前添加global balance声明,否则会抛出局部变量未定义错误
    3. main.py中不能直接调用deposit(),应该调用ATM类的对应方法:Bank.ATM.deposit(amount)

修复后的核心代码示例

修改后的Bank.py

class ATM:
    @staticmethod
    def deposit(amount):
        global balance
        amongus = "Depositing {:.2f}".format(amount)
        print(amongus)
        balance = balance + amount
        return balance
    
    @staticmethod
    def withdraw(amount):
        global balance
        if balance >= amount:
            amongus = "Withdrawing {:.2f}".format(amount)
            print(amongus)
            balance = balance - amount
        else:
            print("Insufficient funds")
        return balance
    
    @staticmethod
    def get_balance():
        global balance
        return balance

balance = 20.00

修改后的main.py

import Bank
import Input
balance = Bank.ATM.get_balance()
amongus = "Starting Balance: {:.2f}".format(balance)
print(amongus)
amount = Input.Validator.get_float("Please enter deposit amount ($0.00 - $1000.00): ",0.00,1000.00)
Bank.ATM.deposit(amount)

内容的提问来源于stack exchange,提问作者Jasnoby Guacamole

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 14:24:01