May-10-2023, 02:56 AM
Besides the error, the traceback should also show you the variable that is causing the problem and the line number.
You can add some print statements on the line before to check what you are assuming. Let's say that I get the error like this:
You can add some print statements on the line before to check what you are assuming. Let's say that I get the error like this:
Error:Traceback (most recent call last):
File "/tmp/indexerr.py", line 4, in <module>
info = mylist[x]
~~~~~~^^^
IndexError: list index out of range
I might add some statements on line 3 that give me more information:print(f"mylist has a length of {len(mylist)} and x has a value of {x}")Now I can run the program and get more info:
Output:mylist has a length of 15 and x has a value of 30
...
Oh, no wonder I got an index error. Now I can track down why x is 30 here instead of whatever I expected it to be.