Reputation: 21
I'm trying to write a python program that takes a character as input which is going to be an uppercase character; the output should be the next character in the alphabet. But if the input is 'Z', then the output should be 'A'. The following is my code but when I input Y it outputs 'Z' and 'Y':
ino = ord(input())
if ino != 90:
ino += 1
print(chr(ino))
if ino == 90:
print(chr(65))
Upvotes: 0
Views: 56
Reputation: 161
I don't have much experience with python but I can explain it in general programming terms.
Here, you are trying to go in a circular motion, i.e. you want A
to be printed right after Z
which are the first and last elements in a linear formula.
We know the ASCII value of A
is 65 and of Z
is 90 and there are 26
alphabets in English. Now if I subtract the input with 65, I can know it's position from A
. If this position+1 goes past 26, i.e. we exceeded the Z
and should roll back to A
. Here is where we can make use of Modulo operator (%). So when we modulo new position with 26, we roll back to the A
. And since we subtracted 65 in the beginning, we must now add it back to balance the equation and get our real ASCII value back.
So your code might look similar to:
ino = ord(input())
ino = ino - 65
ino = (ino + 1) % 26
ino = ino + 65
print(chr(ino))
Hope this will work for you.
Upvotes: 0
Reputation: 33335
ino = ord(input())
if ino == 90:
ino = 65
else:
ino = ino + 1
print(chr(ino))
Upvotes: 2