-1

in general if-else condtional statements if my given input is alphabet (A-Z). so my output should represent from (0-25) ex: if my input is 'A' then it should return 0 if my input is 'B' the it should return 1 soon.... if my input is 'Z' the it should return 25.

if key=='a':
    return 0
elseif key=='b':
    return 1
elseif key=='c':
    return 2
elseif key=='d':
    return 3
elseif key=='e':
    return 4

but i want to know is there any alternate way to write this code in python3? 1 or 2 lines of code can be apperciated.

khelwood
  • 55,782
  • 14
  • 81
  • 108
sukesh
  • 41
  • 4
  • This is a duplicate post. please refer : https://stackoverflow.com/questions/2802726/putting-a-simple-if-then-else-statement-on-one-line – roshan ok Nov 05 '19 at 15:37
  • 3
    Possible duplicate of [Convert alphabet letters to number in Python](https://stackoverflow.com/questions/4528982/convert-alphabet-letters-to-number-in-python) – khelwood Nov 05 '19 at 15:41
  • 2
    Briefly: `return ord(key.lower()) - ord('a')` – khelwood Nov 05 '19 at 15:42

2 Answers2

2

Seems you are referring to a Ternary operator.

'true' if True else 'false'

Just in case if it helps, instead of using multiple if, elif conditions, you can keep the data in a python dictionary and map the keys, values based on input.

alphaNum = {'a': 0, 'b':1, 'c':2, 'd':3}

user_input = input('Enter an alphabet: ')

if user_input in alphaNum.keys():
    print(alphaNum[user_input])
Srini
  • 187
  • 1
  • 2
  • 13
  • is it possible in reverse like if my input is 1 it should return A – sukesh Nov 06 '19 at 04:54
  • Yes, it is possible. You need to map the user input with the values in the dictionary and return the respective key. `for alpha, num in alphaNum.items(): if num == 3: print(alpha)` – Srini Nov 06 '19 at 14:34
  • Don't use the call to the `keys` method if you don't need to. `if user_input in alphaNum.keys():` could be written as `if user_input in alphaNum:`. And of course according to the [Style Guide for Python Code](https://www.python.org/dev/peps/pep-0008/) `alphaNum` should be named `alpha_num` instead. – Matthias Nov 07 '19 at 11:01
0

You can also define your values in dictionary and then return by key

def example(key):
    tmp_dict = {'a':0,
                'b':1,
                'c':2,
                'd':3,
                'e':5}
    return tmp_dict[key]

print (example('a'))
roshan ok
  • 383
  • 1
  • 6