Search code examples
pythonstringintegerindices

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


okay so i know this probably doesn't look very tidy, but on the line 'FinalMessage' I am getting the error 'string indices must be integers' and I need a little help putting it right and understanding why. Any help appreciated :)

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

Solution

  • You define MonthList as (heh) a list here MonthList = [] . Then you try to use it as an index here NumOfMonth[MonthList], which predictably fails.

    I assume you wanted the Xth month, which would translate into:

    MonthList[NumOfMonth]

    But then you also have a wrong indexation here Interest[MonthList] , which i again, assume , was meant to be InterestList[NumOfMonth]

    EDIT

    As pointed out in the comments, you'd have to convert NumOfMonth to an int first NumOfMonth=int(NumOfMonth)