I am sorry, but I am at a loss here everyone. No real idea where to start. I am new to Python and its been many years since I last tried programming of any kind. I was never very experienced. I am following this Python course online and have come to a dead end on an exercise. It is going off of the previous example.
x = int(input())
if x>=1 and x<=26:
print('letter', x, 'in the alphabet:', chr(ord('A')+(x-1)))
else:
print('invalid input:', x)
This example program converts numbers to letters. So, 'A' = 1 and 'B' = 2. It now wants me to make a program just like this but the opposite. I am supposed to start with this line:
letter = input()
Here is what the exercise describes:
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
Now this is I can do, but not the way it wants me to do it, nor the way I should. I could do something like this:
if letter == 'A':
letter = int(1)
print(letter)
elif letter == 'B':
letter = int(2)
print(letter)
Of course that would be very long and sloppy. Does anyone have any advice for me? This one has me stuck. I'm sorry, I know this is probably very simple, this just seems much more complicated to me than it should be. I have tried looking this up but everything I find online is different enough that I cannot figure out how to implement it into this code. To be honest the chr and ord stuff confuses me greatly. I appreciate it for anyone who stuck around long enough to read this. Thank you. I have no idea what to do anymore with this one. Also, this is my very first time posting anything here, so if I did anything sloppy or wrong, I apologize and will delete/edit it as soon as I can.
The problem can be found here: https://cscircles.cemc.uwaterloo.ca/9-else-and-or-not/
Adding a little information. CScircles requires that A = 1 instead of 0. Thanks for the quick replies. I will be working on this again later today.
You have to use the
ord
function again, that you used in the previous exercise to get the char number of the character. Then you can substract the char value of the characterA
to get a value between1
and26
.The
ord(x)
function accepts a characterx
(e.g. anyUTF8
character) and returns an integer. This integer value represents the number of the character in the encoding table: Let's take a look at the table forascii
below. Here you see thechar
values and thedec
/int
values of the characters. For example the characterA
is represented by theint
value65
, and so on.The
chr(x)
function is doing the opposite: it takes theint
value and returns thechar
which is represented by this, this means: