Trying to create a ROT13 decoder and I found an error I don't quite understand

162 views Asked by At

I'm pretty new to the world of coding in general and after completing a recent Codecademy project themed about cryptography, I was inspired to try creating my own ROT13 decoder using a similar setup, since I've seen ROT13 used a lot on some fansites I've frequented to cover up spoilers. The code I wrote is as follows:

ABCs = "abcdefghijklmnopqrstuvwxyz"
punctuation = ".,?'! "
user_input = input("Enter message to be decoded: ")

def ROT13_decode(message):
    translation = ""
    for letter in message:
        if not letter in punctuation:
            letter_value = ABCs.find(letter)
            translation += ABCs[(letter_value + 13)]
        else:
            translation += letter
    return translation

print(ROT13_decode(user_input))

However, when debugging, I got the following error message:

line 10, in ROT13_decode
    translation += ABCs[(letter_value + 13)]
IndexError: string index out of range

I don't know how my string index can be out of range, when there's only 26 letters to work with. What am I missing?

1

There are 1 answers

1
Xetera On BEST ANSWER

When you add 13 to your letter value you have to be able to loop the result back to the beginning of the alphabet which is the entire trick that makes ROT13 work. If you change your translation code to:

translation += ABCs[(letter_value + 13) % 26]

The upper half of the alphabet which would normally give you a value that's bigger than the length of ABCs is guaranteed to always be less than 26.