mercredi 19 mai 2021

Defining new variable before elif statement that is used as a condition

I'm trying to define a certain logic with if-elif-else statement. But it seems that what seems logical to me turns out to be invalid syntax. And I can't really understand why. I suppose there is a rather simple answer to this.

I wrote some logic as follows:

mylist = ['a', 'aa', 'aaa']

for index, element in enumerate(mylist):
    if index == len(mylist)-1:
        # Case: this is the last element
        pass

    myvar = mylist[index+1]
    elif len(myvar) == 2:
        # Case: this is not the last element and the next element length is 2
        pass

    else:
        # Case: this is not the last element and the next element length is not 2 ()
        pass

The problem is with definition of myvar and the consequent elif statement. This code gives invalid syntax, and pycharm defines it as 'Illegal target for variable annotation'. The question is: why can't the myvar be defined right before the elif statement. Does all conditions has to be predefined before executing the statement even tho the code might not get to a certain elif statement? Or there simply can't be any extra code in between if-elif-else parts? In this case myvar can't be predefined because it might be out of range.

As a solution I made it like this:

for index, element in enumerate(mylist):
    if index == len(mylist) - 1:
        # Case: this is the last element
        pass
    else:
        myvar = mylist[index + 1]
        if len(myvar) == 2:
            # Case: this not the last element and the length of next element is 2
            pass

        else:
            # Case: this is not the last element and the length of next element is not 2
            pass

Aucun commentaire:

Enregistrer un commentaire