1

Write a function

shiftLetter(letter, n)

whose parameter, letter should be a single character. If the character is between "A" and "Z", the function returns an upper case character n positions further along, and "wrapping" if the + n mapping goes past "Z". Likewise, it should map the lower case characters between "a" and "z". If the parameter letter is anything else, or not of length 1, the function should return letter.

Hint: review functions ord() and chr() from the section, as well as the modulus operator %.


Down below is what I worked so far. It should return to A after alphabet is over, but it's not working properly from alphabet x. I guess..? I should subtract 90(Z) - 65(A) in ASCII table for x,y,z but confused about that.

def shiftLetter(letter,n):
    if letter >= 'A' and letter <= 'Z':
        return chr(ord(letter) + n )
   elif letter >= 'a' and letter <= 'z':
        return chr(ord(letter) + n )

print(shiftLetter('w',3))
hursooo
  • 43
  • 5
  • You haven't implemented the "Wrapping" part of the assignment. If you go beyond "Z" or 'z', you need to subtract 26. – Frank Yellin Nov 05 '20 at 01:38
  • Yes, I conceptually know that concept, but having difficulties coding it. Could you let me know how to code it? – hursooo Nov 05 '20 at 01:46

1 Answers1

2

You can use the mod operator to wrap the alphabet:

def shiftLetter(letter,n):
   if letter >= 'A' and letter <= 'Z':
        return chr((ord(letter) - ord('A') + n) % 26 + ord('A') )
   elif letter >= 'a' and letter <= 'z':
        return chr((ord(letter) - ord('a') + n) % 26 + ord('a') )

print(shiftLetter('w',3))   # z
print(shiftLetter('E',3))   # H
print(shiftLetter('Y',3))   # B
print(shiftLetter('f',26))  # f
print(shiftLetter('q',300)) # e

Output

z
H
B
f
e
Mike67
  • 11,175
  • 2
  • 7
  • 15