What I have found so far in many cases python code for checking business logic or any other logic is some thing like below(simplified):
user_input = 100
if user_input == 100:
do_something()
elif user_input > 100:
do_sth_different()
else:
do_correct()
When a new logic need to be checked what new python programmer(like me) do just add a new bock in elif…
What is pythonic way to check a bunch of logic without using a long chunk of if else checking?
Thanks.
The most common way is just a line of elifs, and there’s nothing really wrong with that, in fact, the documentation says to use elifs as a replacement for switches. However, another really popular way is to create a dictionary of functions:
This doesn’t allow for your given
if user_input > 100line, but if you just have to check equality relationships and a generic case, it works out nicely, especially if you need to do it more than once.The try except case could be replaced by explicitly calling get on the dictionary, using your generic function as the
defaultparameter:If that floats your boat.