Python Forum
how do I fix an index error? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: how do I fix an index error? (/thread-39194.html)



how do I fix an index error? - MehHz2526 - Jan-15-2023

I know what an index error is, but all my variables are numbered correctly from 0 to 5 but I still have an index error. I think that the main problem has to do something with this line:
sipDifferenceYear =int(line.split(" ; ")[1].replace("\n",""))
I was told by my teacher to incorporate line.split and for loops which I don't have a good understanding of that, so my code might be hard to understand
def write():        
         with open ("MonthlyRecord.txt","w") as f:
            global sipDifferenceYear
            sipDifferenceYear = 0
            f.write ("SIP:" +str(Name))
            f.write (" ; ")
            f.write ("Expiry:"+str (sipDifferenceYear))
            f.write (" ; ")
            f.write ("£:" +str (totalCost1))
            f.write (" ; ")
            f.write ("£:" +str (totalCost2))
            f.write (" ; ")
            f.write ("£:" +str (totalCost3))
            f.write (" ; ")
            f.write ("£:" +str (finalcost))
            f.write ("\n ")
            exit

def read():
        with open("MonthlyRecord.txt","r") as f :
            lookfor= input ("RE ENTER NAME:") 
            for line in f.readline ():
                Name=(line.split (" ; ")[0])
                sipDifferenceYear =int(line.split(" ; ")[1].replace("\n",""))
                if Name == lookfor:
                    print(sipDifferenceYear)
                    
        
        
        
Name= input("NAME:")
sipDifferenceYear= int(input("sipDifferenceYear:"))
totalCost1 = float(input("totalCost1:"))
totalCost2 = float(input("totalCost2:"))
totalCost3 = float(input("totalCost3:"))
finalcost = float(input("finalcost: "))
write()
read() 
Error:
Traceback (most recent call last): File "main.py", line 40, in <module> read() File "main.py", line 26, in read sipDifferenceYear =int(line.split(" ; ")[1].replace("\n","")) IndexError: list index out of range
Output:
NAME:meh sipDifferenceYear:0 totalCost1:2.0 totalCost2:2.0 totalCost3:2.0 finalcost: 6.0 RE ENTER NAME:meh Traceback (most recent call last): File "main.py", line 40, in <module> read() File "main.py", line 26, in read sipDifferenceYear =int(line.split(" ; ")[1].replace("\n","")) IndexError: list index out of range



RE: how do I fix an index error? - Gribouillis - Jan-15-2023

line.split(" ; ") returns a list. If this list has length smaller or equal to 1, there is no item at index [1] in the list. For some reason, one of the lines in MonthlyRecord.txt has a different format from what you expect. Try to find this line first.