CS Circles 9 (Else, And, Or, Not) Coding Exercise: 26 Letters

Write a program which does the reverse of the example above: it should take a character as input and output the corresponding number (between 1 and 26). Your program should only accept capital letters. As error-checking, print invalid if the input is not a capital letter.

First consider the ordinal value of the letter that is input:


In [9]:
letter = 'A'
ord(letter)


Out[9]:
65

We want 'A' to be 1 so we need to subtract 64:


In [10]:
ord(letter) - 64


Out[10]:
1

How do we check that the letter is invalid? Simply check if the ordinal value - 64 is less than 1 or greater than 26:


In [11]:
if ord(letter) - 64 < 0 or ord(letter) - 64 > 26:
    print ("invalid")
else:
    print (ord(letter) - 64)


1