6

i have this long and ugly else if statement in python, is there a way to condense it into a shorter block of code maybe on one line or two if possible because it seems like there would be a way of shortening a piece of code like this

if p == "A": y = 10        
elif p == "B": y = 11
elif p == "C": y = 12
elif p == "D": y = 13
elif p == "E": y = 14
elif p == "F": y = 15

3 Answers3

6

have a dictionary containing values of y given p

p={"A":10,.....}
y=dict[p]
user3684792
  • 2,542
  • 2
  • 18
  • 23
  • 2
    You'd be better off using `.get(p, None)` as you can supply an optional default argument to avoid throwing exceptions. –  Aug 26 '14 at 13:21
  • 1
    Or even better use a `DefaultDict` so you don't have to use the `.get(key, defaultValue)` form. – helpermethod Aug 26 '14 at 13:47
2

Use a dict:

choice = {
    "A": 10,        
    "B": 11,
    "C": 12,
    "D": 13,
    "E": 14,
    "F": 15
}[selected]

ie.

selected = "A"
choice = {
    "A": 10,        
    "B": 11,
    "C": 12,
    "D": 13,
    "E": 14,
    "F": 15
}[selected]

print choice
>>> 10

By immediately adding the [selected] at the end of the dict can easily get a dictionary to behave like a control flow statement. Using this pattern it will always evaluate to the case.

agconti
  • 17,780
  • 15
  • 80
  • 114
2

There is no possibility to shorten this piece of code. As you may have noticed, python does not provide any switch-case statement.

Depending on your usage, you could change it to a dictionary or recalculate it by value:

values = { "A": 10, "B": 11, "C": 12, "D": 13, "E": 14, "F": 15 }
y = values[p]

or

y = ord(p) - ord("A") + 10
roalter
  • 259
  • 1
  • 2
  • 13