Coded Correspondence: Index Out of Range

Hello everyone. I’m currently 41% through the ‘Data and Programming Foundation for AI’ course and I’m at the Coded Correspondence Project. It wants me to decode a message called the Caesar Cipher. Every letter in the message is supposed to have an offset of 10. The actual coded message is below. I learned about the find() function which I’m not sure the course actually bring up even to this point. I figured make a function that finds the coded letter in string of the alphabet, add 10 to find the decoded letter, add it to a new string and return the decoded string but it says ‘Index out of range’. I suppose it’s trying to add an offset of 10 but is going our of range of the alphabet string. Does anyone know how to solve for this issue? You can check what I’m trying to do below and tell if anything I’ve done is at all good or if I’m just off completely. Let me know. I’d really appreciate feedback.

coded_message = "xuo jxuhu! jxyi yi qd unqcfbu ev q squiqh syfxuh. muhu oek qrbu je tusetu yj? y xefu ie! iudt cu q cuiiqwu rqsa myjx jxu iqcu evviuj!" alphabet = "abcdefghijklmnopqrstuvwxyz" def message_decoder(message): message_decoded = '' for character in message: if character in alphabet: alphabet_letter = alphabet.find(character) message_decoded += alphabet[alphabet_letter + 10] return message_decoded print(message_decoder(coded_message))

You’re on the right track by attempting to decode the message with a Caesar Cipher! However, the issue with the Index out of range error arises when the offset (in your case, 10) causes you to go beyond the end of the alphabet string.

To fix this, you need to wrap around to the beginning of the alphabet if the index exceeds the length of the alphabet. This can be achieved by using the modulo operator (%). The modulo operation will ensure that if the index exceeds the length of the alphabet, it wraps around to the beginning.

Here’s an updated version of your code that handles this issue (you can try it here):

coded_message = "xuo jxuhu! jxyi yi qd unqcfbu ev q squiqh syfxuh. muhu oek qrbu je tusetu yj? y xefu ie! iudt cu q cuiiqwu rqsa myjx jxu iqcu evviuj!"
alphabet = "abcdefghijklmnopqrstuvwxyz"

def message_decoder(message):
    message_decoded = ''
    for character in message:
        if character in alphabet:
            # Find the index of the character in the alphabet
            alphabet_letter = alphabet.find(character)
            # Add 10 to the index and use modulo to wrap around
            decoded_index = (alphabet_letter + 10) % len(alphabet)
            # Append the decoded character to the result string
            message_decoded += alphabet[decoded_index]
        else:
            # If the character is not in the alphabet (like spaces or punctuation), keep it unchanged
            message_decoded += character
    return message_decoded

print(message_decoder(coded_message))
1 Like