简体   繁体   中英

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

Yes, there can't be any extra code in between if-elif-else . So you should just put myvar before the if-elif-else .

for index, element in enumerate(mylist):
    myvar = mylist[index+1]
    if index == len(mylist) - 1:
        pass
    elif len(myvar) == 2:
        pass

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