I just wrote my first Python program. How exciting.
So let's imagine we can convert the letters into the numbers 0 to 25 (zero-basing, because that's how we roll). Reversing the original shift will involve subtracting the shift from those numbers. But if we get a result outside of that range, we want to convert it back into that range. The usual tool for doing this is modulus, which is the % symbol in Python. And indeed if we look at this, (-1 % 26) is 25, meaning that subtracting 1 from 0 will roll us back around to 25. Adding 1 to 25 yields 26 and (26 % 26) is 0, so that all seems in order as well. So far, assuming we had the numbers 0 to 25 in the variable letterCode, it would look like this:
Quote:
(letterCode - shiftValue) % 26
So how do we convert letters to numbers and back again? All letters have sequential ASCII codes, we could use that. Python provides the ord() and chr() functions for converting back and forth. ord('A') turns out to be 65, so if I subtract 65 from the ord() value of each letter I'll get numbers between 0 and 25. Then after I do the mathsy stuff above, I can add 65 to it again and convert back to letters.
Quote:
chr(((ord(char) - 65 - shiftValue) % 26) + 65)
The full program:
Code:
cipherText = "FRQJUDWXODWLRKVBRXKDYHGHFOBSWHGWKHPHVVDJH"
shiftValue = input("Please enter an integer shift value from 1 to 26: ")
result = ""
for char in cipherText:
result = result + chr(((ord(char) - 65 - shiftValue) % 26) + 65)
print result
When run and given "3" this returns the following:
Quote:
CONGRATULATIOHSYOUHAVEDECLYPTEDTHEMESSAGE
Someone screwed up the cyphertext.
Note, the above only works for capital letters. You can run whatever the Python equivalent of ToUpper is on the cyphertext to get around this.