I was wondering if someone could tell me the pythonic way to check out the following.
I have a 6 bit binary number and want to check with its decimal values. Using mathematical function is one way but still it would require that I write around 2**6 if constructs.
So I wanted to know if there's an easier statement to write it.
Also assume that lets say it's not binary then what's the better way to check for 2**6 values in python.
if(a==1):
....
else:
if(a==2)
.....
One way is saving it in a list and checking it with the indexes but still that would require that many if-else I guess.....
Thanks ....
Use a dictionary mapping values into outcomes (which can be functions in Python).
For example:
Naturally, how this works depends on your
....
, but this construct can be very flexible. The most important feature of this approach is that this dictionary can be populated programmatically, and you don't need to write a lot of manual assignments. It's of course also much more efficient than going over many values with nestedif
statements (orelsif
)I would use a decorator to map into a dictionary based dispatch:
To add to the responses of the others, you should read about the recommended Python style in PEP 8.
With your
if
version, the brackets are undesirable and spacing is desirable:Based on the somewhat vague information in the question and what I've been able to gather from the OP's comments, here's my guess:
Personally I prefer a if/elif if I am understanding your
...
so your:
Becomes this if you use
if elif
ladder:You can also use Python's version of a conditional expression for simple ladders:
Or even dictionaries:
There is a great discussion on Python forms of switch-case in this SO post.