The elif statement in Python

Wikipedia gives the following example for and else-if construction in programming (I don’t know which language exactly this is, from the context of the Wiki article I would suppose it’s Ada):

if condition then
–statements
elseif condition then
– more statements
elseif condition then
– more statements;

else
– other statements;
end if;

Now obviously all the statements introduced by elseif are executed if and only if the preceding conditions introduced by if or elseif are not met.

But note the end if at the very end of this snippet. I suppose this marks the end of the block introduced by the initial if. After this endif, the if condition, on which all subsequent elseifs hinged, does not matter anymore.

But Python (where the equivalent to elseif above is elif) does not seem to require an end if - at least I’ve tried code that had if blocks but no end if, and it ran fine. So where does the block end in which the initial if determines what the subsequent elifs refer to? I cold certainly mark it with an else, but that seems optional. It can’t be a matter of indentation either - in the elif examples that I’ve seen, that command is not indented to the right of the preceding if but stands at the same level of indentation. So am I correct in assuming that the if condition that defines subsequent elifs is only the immediately preceding one, and that earlier ifs at a previous point in the program don’t affect the meaning of a subsequent elif anymore as soon as a new if has intervened?

Indentation does matter. elif will reference the previous if as long as there’s no other unindented line in between them. If there is one, it’s a syntax error.

This is fairly easily tested, is it not? Just open a python terminal and try it out.

elif is just a concatenation of else and if. The else to an if has to be the next statement at the same level of indentation as the if. Multiple consecutive elif just chains this, so the else of the next elif belongs with the if of the previous one.

Yes.

In Python, the if, elif, and else lines must all be at the same indentation.

Or more general, in python all code blocks end when you drop a level of indentation.

statement a
    more statements
    even more statements
statement in new block

in python is equivalent to

statement a {
    more statements
    even more statements
}
statement in new block

in a language that use brackets to define code blocks. In that language the indentation of the second and third line is just for readability, in python they are what defines the block. And if “statement a” is an if statement you can’t throw in an else anywhere later in the code other than right after the end of the block defined for the if-statement.