简体   繁体   中英

I keep on getting index error. i dont know where should i change my code. here are my codes

def disp_sss():
    print ("\n\nList of SSS loans\n")
    print ("EmployeeNo        SSS        Deduction")
    for idx in range(len(EmpNo)):
        print (" {0:15} {1:10s} {2:10.2f}".format(EmpNo[idx], SSSLoan[idx], float(MonthlyDeduction[idx])))

im trying to display the data from a text file. this is the erro message. line 87, in disp_sss print (" {0:15} {1:10s} {2:10.2f}".format(EmpNo[idx], SSSLoan[idx], float(MonthlyDeduction[idx]))) IndexError: list index out of range

the thing is, when i run the program, it displays all the data but after dsiplaying the data, the error start to appear. here is the display im getting respectively. EmployeeNo SSS Deduction 123 500 200.00 a1001 300 20.00

My best guess is that your SSLoan/MonthlyDeduction do not have the same length as EmpNo.

TO debug, first try just removing those two at once, then add it one by one to see where the real problem is.

Alternatively, you might consider storing them into a dataframe and display the dataframe, which might have better look.

You're iterating an index over the list EmpNo , but you're trying to use the same index on two other lists, SSSLoan and MonthlyDeduction , so if any of the two lists has fewer items, it would cause an IndexError when the iteration gets to a point where the index exists for EmpNo but not for SSSLoan or MonthlyDeduction .

You should make sure that the 3 lists are of equal length. Alternatively, you can use zip the 3 lists so that the iteration would end when the shortest list is exhausted:

def disp_sss():
    print("\n\nList of SSS loans\n")
    print("EmployeeNo        SSS        Deduction")
    for row in zip(EmpNo, SSSLoan, MonthlyDeduction):
        print(" {0:15} {1:10s} {2:10.2f}".format(row))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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