Maybe this counts as mind blowing as well. The elif if python does not work any differently than the else if in Java. The only valid reason for having this elif construct is the formatting. In Python you would have to use correct spacing when using else if
ifgrade>=90:print("You got an A!")else:ifgrade>=80:print("You got a B!")else:ifgrade>=70:print("You got a C!")else:ifgrade>=60:print("You got a D!");else:print("You got an F!");
There is no difference in program flow or even speed when you use an elif construct. The blocks are just arranged in a nicer way. Very much like, when in Java you are using
elseif(x){System.out.println("Stuff")}
instead of
else{if(x){System.out.println("Stuff")}}
The solution in your case to get 'nicer looking' code without the usage of else so much is something like:
I was just wondering to myself why python would have a separate elif keyword. But of course it makes sense because of whitespace having meaning in python.
Thanks!
I teach computer science to undergrads and write for The Renegade Coder. I'm most likely taking care of my daughter, watching the Penguins, or reading manga.
Location
Columbus, Ohio
Education
B.S. in CE from CWRU 2016; M.S. in CSE from OSU 2020; PhD in EED from OSU 2024
Maybe I was unclear, but the reason that this is so mind blowing to me is that else if isn’t a keyword. There is only elseand if. Python had to introduce a third keyword because else if isn’t valid syntax. In other words, else if comes for free in C-like languages due to the language grammar, and I had just assumed it was a special token.
Maybe this counts as mind blowing as well. The
elifif python does not work any differently than theelse ifin Java. The only valid reason for having thiselifconstruct is the formatting. In Python you would have to use correct spacing when usingelse ifThere is no difference in program flow or even speed when you use an
elifconstruct. The blocks are just arranged in a nicer way. Very much like, when in Java you are usinginstead of
The solution in your case to get 'nicer looking' code without the usage of
elseso much is something like:P.S. What is wrong with you Americans? Don't you care for the alphabet? What happened to 'E'?
I was just wondering to myself why python would have a separate elif keyword. But of course it makes sense because of whitespace having meaning in python.
Thanks!
Quote from python documentation to back me up on this:
Maybe I was unclear, but the reason that this is so mind blowing to me is that
else ifisn’t a keyword. There is onlyelseandif. Python had to introduce a third keyword becauseelse ifisn’t valid syntax. In other words,else ifcomes for free in C-like languages due to the language grammar, and I had just assumed it was a special token.gave a heart just beacuse of P.S. :D