Im trying to create a Ceaser Cipher function in Python that shifts letters based off the input you put in.
plainText = input("Secret message: ")
shift = int(input("Shift: "))def caesar(plainText, shift): cipherText = ""for ch in plainText:if ch.isalpha():stayInAlphabet = ord(ch) + shift if stayInAlphabet > ord('z'):stayInAlphabet -= 26finalLetter = chr(stayInAlphabet)cipherText += finalLetterprint(cipherText)return cipherTextcaesar(plainText, shift)
For example, if I put "THE IDES OF MARCH" as my message and put 1 as my shift, it outputs "UIFJEFTPGNBSDI" when it is meant to output "UIF JEFT PG NBSDI." It doesn't keep the spaces and also shifts things like exclamation marks back also when it should leave them as is. Letters should also wrap meaning if I put shift as 3, an X should go back to A.
To fix the spacing issue, you can add an else
to if ch.isalpha()
and just append the plain text character to the cipher text. This will also handle punctuation and other special, non-alpha characters.
To handle wrapping (e.g. X to A), you'll want to use the modulo operator %
. Because A
is the 65th ASCII character and not the 0th, you'll need to zero-base the alpha characters, then apply the mod, then add back the offset of 'A'. To shift with wrap-around, you can do something like: final_letter = chr((ord(ch) + shift - ord('A')) % 26 + ord('A'))
. Note the 26 comes from number of letters in the Latin alphabet.
With these in mind, here is a full example:
plain_text = input("Secret message: ")
shift = int(input("Shift: "))def caesar(plain_text, shift): cipher_text = ""for ch in plain_text:if ch.isalpha():final_letter = chr((ord(ch) + shift - ord('A')) % 26 + ord('A'))cipher_text += final_letterelse:cipher_text += chprint(cipher_text)return cipher_textcaesar(plain_text, shift)
Sample input:
plain_text = "THE IDES OF MARCH"
shift = 1cipher_text = caesar(plain_text, shift)
print(cipher_text)
# UIF JEFT PG NBSDI