0

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?

Hugh
  • 23
  • 2

3 Answers3

4

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]
user2390182
  • 72,016
  • 6
  • 67
  • 89
  • Down-vote because this is an overkill for such simple problem. – Dawid Laszuk Dec 23 '17 at 20:16
  • John's answer is great, or even your indexing on string. Dictionary is great in general, but for this specific problem it just feels too much. – Dawid Laszuk Dec 23 '17 at 20:25
  • I'm happy to remove my downvote and add upvote if you reconsider changing order in your answer: list, manual dict and fancy zip. Don't get me wrong, I like your suggestions, but if you are limiting to this specific question than it might be slightly misleading without extended explanation. (In my opinion, obviously.) – Dawid Laszuk Dec 23 '17 at 20:27
  • I think Dawid Laszuk's answer is better as it provides code based at programmers at all levels, so I accepted his answer, however I will leave an upvote because this did help <3 – Hugh Dec 23 '17 at 20:41
3
chr(ord('a') + var -1) 

would be the answer

heemayl
  • 39,294
  • 7
  • 70
  • 76
Ctznkane525
  • 7,297
  • 3
  • 16
  • 40
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.

Dawid Laszuk
  • 1,773
  • 21
  • 39
  • LOL, you copy my solution into yours and downvote it at the same time. – user2390182 Dec 23 '17 at 20:22
  • @schwobaseggl Because in general I like your answer, but not for this problem specifically. – Dawid Laszuk Dec 23 '17 at 20:27
  • I can understand the others, however I think yours is best for others who may view this question, as it's formatted very well and provides answers aimed at programmers at all levels. Upvoted & Accepted. – Hugh Dec 23 '17 at 20:40