I have a variable var
which could contain any number from 1-5. I want to run an if
statement on each possibility. i.e.
if var == 1:
num = "a"
if var == 2:
num = "b"
...
Is there an easier way to do this?
You could do
num = dict(zip(range(1,6), 'abcde')).get(var, 'f') # f in case you need a default
using the dictionary pattern to mimick a switch. You just build a mapping for all the cases and use dict.get
with a default value:
d = {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}
num = d.get(var, 'f')
If your data and mapping are as regular and trivial as in your example, there are even easier ways, e.g.:
num = 'abcde'[var - 1]
That depends on your use case. Although provided by others answer are correct, they have complexity added to them, which might not be easy to read or doing way to much than it's needed. Let me suggest few options.
Simple and explicit
Use if/elif/else
for explicitly stating what you want.
if var == 1:
num = "a"
elif var == 2:
num = "b"
elif var == 3:
...
else:
num = "f"
Advantages: Each check is one operation and it doesn't go to other statements unless it needs to. Besides you clearly see what's going on and maintaining this is simple and trivial.
Disadvantage: It doesn't look cool, and doesn't show off your hard earned Python experience points. Bite the bullet.
List index Since your key is an integer, you can use it to index position in a list.
#values = ['a','b','c','d','e','f']
values = "abcdef"
num = values[var-1] # 0 < var <= len(values)
Advantages: Easy to maintain and expand. Looks good and only two lines. Use whenever you can convert your key into ordered numbers.
Disadvantages: You can only return element from the list and each element is evaluated before returning. In case of strings all is fine.
Dictionary approach
Uses dictionary with natural handling of keys and values. Examples as uggested by @schwobaseggl.
num = dict(zip(range(1,6), 'abcde'))[var]
or
d = {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}
num = d[var]
Advantages: It has natural structure of key and value. Flexibility in keys, which can be ints or strings, and values, which are any objects. Python is also visibly getting better with handling dictionaries. Use for flexibility with keys.
Disadvantage: Potential overkill. In your case there's no advantage for using this, but still have to generate dictionary object. In general, all elements are evaluated on constructing dictionary. More expensive to create than a list.
Best for your case
Integer to string can be easily done, as John Kane suggested, by finding character in alphabet at given position.
chr(ord('a') + var - 1)
or
ord_a = ord('a') # alphabet start position
num = chr(ord_a + var - 1) # return var's character from alphabet
Advantage: This simply states to return var's position from alphabet starting with a
. Definitely the most efficient way for your problem.
Disadvantage: Specific only to stated question.