Python : Avoiding multiple if-elif-else

Abhishek Inani
2 min readJul 7, 2020

--

While coding we come up with many situations where code looks absurd.
Logically being correct but, we still can improve the readability and optimize it.

Many languages provides one and only one way to approach the problem, while Python may have few more.

Though, one of The Zen of Python says:

There should be one-- and preferably only one --obvious way to do it.

But, I was little bit more curious and could find few obvious ways to change traditional if-elif-else conditions in Python.

Python’s if-elif-else
Python doesn’t have switch statement like other languages, so the only way it can be handled in Python is if-elif as below:

But, that’s not the Pythonic way of approaching the problem.

Actually:
Using multiple if-elif in Python is like you are not doing justice with this powerful language.

Converting if-elif to Dictionary
The Pythonic way to change the multiple if-elif is dictionary as below:

Looks, interesting!. Isn’t it ?
If you ask me, my answer is No.
What happened if there are 100’s of such test cases mapping. This will again flood dictionaries with 100’s of keys and code looks again absurd.

But, as promised Python had it’s own way to handle such things also

Many of us would not spot a bigger difference in above 3 methods, but first two methods keep increasing as the no. of test cases grows. While the last method will remain same and can handle up to 100 test cases mapping.

So, it will add a great readability and optimized performance to Python’s interpreter.

Conclusion:
Python comes with battery included, but sometimes we need to utlize those batteries very well.

Happy Coding, the Pythonic way !

--

--

Abhishek Inani
0 Followers

S/W Automation Tester | Blogger | Traveller | Explorer | Data Analyst