Viktor Mellgren
Viktor Mellgren

Reputation: 4506

for - else vs for elif

i thought that elif: was the shorthand for

else:
     if:

but it's not possible to use

for - elif:

only

for - else: if:

in this code:

for line in source:
    change_next = False
    for dataset,artnr,revision in datasets:
        if dataset in line:
            change_next = True
            print "  **  " + dataset + " found"
            datasets.remove((dataset,artnr,revision))
            break
    else:
        if line.startswith("DstID:"):
            print line.replace("DstID:","").rstrip()

    if change_next and "Partno:" in line:
        destination.write("Partno: " + artnr + "\n")
        print "Partno: " + artnr
    elif change_next and "Revno:" in line:
        destination.write("Revno:" + revision + "\n")
        print "Revno:" + revision
    else:
        destination.write(line)

Thanks for the response so far, my question now is rather: is this the way to do it? if a line does not have any (of the known)datasets in it, then i want to print it if it is a dataset?

Upvotes: 11

Views: 9997

Answers (4)

kindall
kindall

Reputation: 184131

elif: isn't a macro that expands to else: if, it is a syntactical element that is valid only in the context of an if: statement. Ordinarily, else: if would open a new if block; however, elif: doesn't do that.

Upvotes: 13

Silas Ray
Silas Ray

Reputation: 26150

The for else is a special case usage, not the same as the if elif structure. elif doesn't really make sense in the context of for anyway, as the meaning of the for else is "if we have completed the loop without breaking, do this thing". That's binary logic. elif doesn't make sense in the context of this binary decision.

Upvotes: 10

uselpa
uselpa

Reputation: 18917

The 'else' you refer to is tied to the 'for' command, not to an 'if' command. 'elif' only makes sense when used with an 'if' command.

With the 'for' command, the 'else' block is executed only if the 'for' block is not prematurely ended by a 'break' command, see paragraph 4.4.

Upvotes: 5

ecatmur
ecatmur

Reputation: 157334

Correct. The same goes for else in try .. except .. else.

Upvotes: 9

Related Questions