How would i write a program that asks for you to input a letter (a for example) and how many letters you want to shift (3 for example) and gives you the decoded letter (D)? Also how would you loop it so it goes from Z and starts over with A instead of going to other characters in ASCII using ord()? Timely response would be greatly appreciated!

Heres what i have so far.. i can get the shift but i cant figure out how to loop it back from a to z. Do you use xrange?

NumberShift = input("Enter the shift amount:")
Letter = raw_input("Enter the letter:")
CodedLetter = ord(Letter)+ Shift
print "The cyphered letter is:", chr(CodedLetter)

One way to do this is using a shifted alphabet, here is a simple example:

``````# rotation_crypt1.py
# use the index in the regular alphabet and apply it to a
# shifted alphabet (all upper case letters for simplicity)

import string

alpha = string.ascii_uppercase

shift = 3
# shift the alphabet with slicing
shift_alpha = alpha[shift:] + alpha[:shift]

# testing
letter = 'X'
coded = shift_alpha[alpha.find(letter)]
print "%s shifted %d gives letter %s" % (letter, shift, coded)

letter = 'Z'
coded = shift_alpha[alpha.find(letter)]
print "%s shifted %d gives letter %s" % (letter, shift, coded)

letter = 'A'
coded = shift_alpha[alpha.find(letter)]
print "%s shifted %d gives letter %s" % (letter, shift, coded)

"""my test result -->
X shifted 3 gives letter A
Z shifted 3 gives letter C
A shifted 3 gives letter D
"""``````

This one works too, for uppercase letters

``````>>> def shifted(letter, shift):
...  return chr(ord('A') + (ord(letter) + shift - ord('A')) % 26)
...
>>> shifted('C', 3)
'F'
>>> shifted('Z', 3)
'C'
>>> shifted('X', 3)
'A'
>>> shifted('M', 3)
'P'
>>> shifted('M', -3)
'J'
>>> shifted('A', -3)
'X'
>>> shifted('A', -3000000)
'K'``````