does python allows elif statement without else statement?


While teaching python to a friend i tried this statement :

val = "hi"
if (val=="hello") or ("w" in val):

And to my great surprise it worked. I always tought in Python you couldn’t do an elif without else.
Has it been always like that or the syntax has changed since a particular version?

Asked By: djohon



else is optional, and follows any number of elif statements.

From the specification of version 1.6:

if_stmt:        "if" expression ":" suite
               ("elif" expression ":" suite)*
               ["else" ":" suite]

The * in this syntax means zero or more elements, and [ and ] means an optional element.

Python 1.6 was the first version released as open source. That said, I’m almost certain it has always been like that, because it is standard among most, if not all, programming languages.

Answered By: Emanuel P

This has worked in all versions, just without another case you don’t consider the case where if and elif conditions are not accepted.

Answered By: Jgold
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.