Coded correspondence function spaces

Hello, I have a problem with this piece of code. Instead of translating the sentence with spaces to separate the words it just puts everything together into one long string of letters. Although the letters do get shifted by the correct amount and the punctuation remains unchanged, for some reason the spaces disappear. The previous loops I’ve done in this exercise worked fine and it was only when I put it all into a function that it started doing this. Any help would be appreciated!

def decoder(message, offset):
alphabet = “abcdefghijklmnopqrstuvwxyz”
punctuation = ".,?'! "
translated = “”
for letter in message:
if not letter in punctuation:
letter_index = alphabet.find(letter)
translated += alphabet[(letter_index + offset) % 26]
else:
translated += letter
return translated

print(decoder(“bqdradyuzs ygxfubxq omqemd oubtqde fa oapq kagd yqeemsqe ue qhqz yadq eqogdq!”, 14))

output: performingmultiplecaesarcipherstocodeyourmessagesisevenmoresecure!

Seems to work fine.
Check your indentation on the loops, the if and the else

def decoder(message, offset): alphabet = "abcdefghijklmnopqrstuvwxyz" punctuation = ".,?'! " translated = "" for letter in message: if not letter in punctuation: letter_index = alphabet.find(letter) translated += alphabet[(letter_index + offset) % 26] else: translated += letter return translated print(decoder("bqdradyuzs ygxfubxq omqemd oubtqde fa oapq kagd yqeemsqe ue qhqz yadq eqogdq!", 14))

Next time, use the </> button and put your code on lines between the ``` and ``` so that your code keeps its formatting (like indents and stuff) in the post.

2 Likes