jeudi 8 septembre 2016

Getting 'IndexError: string index out of range' in an if statement that shouldn't be entered

I am iterating through a text file line by line, and checking a few conditions with if statements. But I am getting an IndexError and I cannot understand why it is occurring.

Here is the abstract of my code structure:

while True:
    line = a.readline()
    res = line.find(',')

    var = line[res+1:]

    if var != '' and var != 'a':
        if 'x' in var or 'y' in var and var[-3] == 'z':
            do something;

The problem is, I am getting the IndexError when var is 'a'. The error seems to occur because I am referring to index [-3] in var, but since var is a, it is not supposed to go in to the if statement.

When I run my program up to the line where the error occurs and I print var, it prints 'a'.

I was wondering if there are any rules in python that doesn't even allow writing code that indexes out of range in if statements, even when it is supposed to pass the if condition.

Does anyone have ideas?

Aucun commentaire:

Enregistrer un commentaire