+ 1

Ending an if-elif-elif-elif statement-code-block with no 'else' at the end?

It seems that the last elif-condition in an if/elif/elif/elif chain can serve the same purpose as an else condition. Is it considered 'bad practice' to end such a code block without an 'else' at the end?

23rd Apr 2017, 9:17 PM
Lium Goon
Lium Goon - avatar
4 Answers
+ 8
When you use 'else' in the end, you make sure that the indented code block inside it *will* get executed if *all* former conditions are not met (equal False). So you may understand it as 'if anything else happens' then execute the 'else' clause. You may skip 'else' if you know what you are doing - either you covered *all* possible conditions with if/elif or there is no particular reason to execute anything with regards to the case if all those elifs are False.
23rd Apr 2017, 9:44 PM
Kuba SiekierzyƄski
Kuba SiekierzyƄski - avatar
+ 3
Essentially, yes. elif True would work like else in this case.
24th Apr 2017, 7:09 AM
Kuba SiekierzyƄski
Kuba SiekierzyƄski - avatar
+ 2
@ Kuba +1 - thanks for your response. I've been experimenting in the playground... Would it be true to say that an if-statement could be ended with either... elif 1 == 1: print('this') or else: print('this') ... and that either one would serve the same purpose in all situations.
24th Apr 2017, 12:44 AM
Lium Goon
Lium Goon - avatar
0
CODE: z=3 if z==1: print("1") elif z==2: print("2") elif z==4: print("4") OUTPUT: No output. Here the last 'elif' doesn't work like 'else'. It's just another specific condition. Bad practice, I don't know. But, sometimes you are just bothered about few specific cases and don't have the time to explore the ocean called, 'else'.
11th May 2020, 8:01 AM
Saunak Dey
Saunak Dey - avatar