繁体   English   中英

为什么在此行代码中出现错误“字符串索引必须为整数”?

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

好的,所以我知道这看起来可能不太整洁,但是在“ FinalMessage”行上,我得到了“字符串索引必须是整数”的错误,我需要一点帮助将其正确并理解原因。 任何帮助表示赞赏:)

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 :)")

通过int(NumOfMonth)NumOfMonth转换为整数

该行应为:

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

您的主要问题是您混淆了列表索引。 您想将NumOfMonth放在[]而不是外面。 这也发生在InterestListTotalBalance中。

在行中

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] ,该索引NumOfMonth[MonthList]失败。

我假设您想要第X个月,它将转换为:

MonthList[NumOfMonth]

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

编辑

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM