Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

does python allows elif statement without else statement?

Tags:

python

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?

like image 399
djohon Avatar asked Apr 24 '26 20:04

djohon


1 Answers

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.

like image 198
Emanuel P Avatar answered Apr 27 '26 08:04

Emanuel P



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!