为什么我在这行代码中收到错误 'string indices must be integers'?

Why am I getting the error 'string indices must be integers' in this line of code?

好的,所以我知道这可能看起来不太整洁,但是在行 'FinalMessage' 上我收到错误 'string indices must be integers',我需要一些帮助来纠正它并理解原因。任何帮助表示赞赏:)

StartBalance = input("Enter a Start Balance - £")

InterestRate = input("Enter Interest Rate - %")

StartBalance = float(StartBalance)
InterestRate = float(InterestRate)
InterestRate = InterestRate/100

TotalBalance = StartBalance

MonthList = []
InterestList = []

Months = 24

print("Month     Interest      Total Balance")
for Months in range(0,25):
 Interest = TotalBalance*InterestRate/12
 TotalBalance = TotalBalance + Interest

  if Months < 10:
     message = " %d         %6.2f          %6.2f" %(Months, Interest, 
TotalBalance)
  else:
   message = " %d        %6.2f          %6.2f" %(Months, Interest, 
TotalBalance)
print(message)
MonthList.append(Months)
InterestList.append(Interest)

EndOfInput = False

while EndOfInput == False:
  NumOfMonth = input("Enter Month to see Interest and Balance - ")
  FinalMessage = float(NumOfMonth[MonthList]), float(Interest[MonthList]), 
float(TotalBalance[MonthList])
  print(FinalMessage)

  Response = ""
  while Response != "Yes" and Response != "No": 
    Response = input("Would you like to see another Month? - ")
    if Response == "Yes":
     if Response != "Yes" and Response != "No":
       print("Invalid input, please enter Yes or No")

if Response == "No":
   EndOfInput = True

print("Thank you for using this program, Goodbye :)")

行中

FinalMessage = float(NumOfMonth[MonthList]), float(Interest[MonthList]), float(TotalBalance[MonthList])  

您正在使用 MonthList 作为列表索引。另请注意 totalBalanceInterestfloat 对象而不是列表对象或可迭代对象。这使得 Interest[NumOfMonth]TotalBalance[MonthList] 无效。

应该是

   FinalMessage = float(MonthList[int(NumOfMonth])), InterestList[int(NumOfMonth]), TotalBalance  

您在此处将 MonthList 定义为(呵呵)列表 MonthList = []。然后你尝试在此处将其用作索引 NumOfMonth[MonthList],这可想而知会失败。

我假设你想要第 X 个月,这将转化为:

MonthList[NumOfMonth]

但是你在这里也有一个错误的索引 Interest[MonthList] ,我再次假设,这应该是 InterestList[NumOfMonth]

编辑

正如评论中所指出的,您必须先将 NumOfMonth 转换为 int NumOfMonth=int(NumOfMonth)

通过int(NumOfMonth)

NumOfMonth转换为整数

该行应该是:

FinalMessage = float(MonthList[NumOfMonth]), float(InterestList[NumOfMonth]), float(TotalBalance)

您的主要问题是您混淆了列表索引。您希望 NumOfMonth[] 内部,而不是在外部。 InterestListTotalBalance 也发生了这种情况。