Caesar Cipher – Code

A Python version of the Caesar cipher might look like this:


def ApplyCaesarCipher(message, shiftSize):

outputText = ""
# Convert message to uppercase.
message = message.upper()
# Work through each character in the message.
for position in range(0, len(message)):

letter = message[position]
# Ignore all characters that are not letters
if letter in LETTERS:

# Turn letter into number, and subtract 65 (A = 65 in ASCII, Z = 90).
letterValue = ord(letter) - 65
# Add shift to letterValue and apply modular division
letterValue = letterValue + shiftSize
letterValue = letterValue % 26
# Convert result back to a letter, remembering to add 65 back on again first
newLetter = chr(letterValue + 65)
# Add new letter to output text.
outputText = outputText + newLetter


# Non-letters can be added to output text without any changes being made.
outputText = outputText + letter

return outputText

message = ""
# Keep prompting the user until they enter a message
while message == "":

message = input("\n\nPlease enter the message to be used:\n")

shiftSize = ""
# Keep prompting the user until they enter a valid shift size
while shiftSize == "":

shiftSize = input("\n\nPlease enter a shift size:\t")

# Try to convert user input to an integer
shiftSize = int(shiftSize)


shiftSize = ""

outputText = ApplyCaesarCipher(message, shiftSize)
print("Output:\n" + outputText)

If you write your own Caesar cipher code, you can check your results against the Create Codes section of this website to verify that it works correctly.

Now that we have got a working Caesar cipher in coded form, we can now turn to the problem of how we get a computer to automatically crack a Caesar cipher for us.

Cipher Challenge competition    Leave feedback