Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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):
    print("hello")    
elif(val=="hi"):
    print("hi")  

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading