The Student Room Group

Computing sceince

So I am not use to python and have been given a quick task, a caesar cipher. I wrote that and they want a key word, which is the infromation needed to trasnform the plaintext into encrypted mesage and is also used by the recipient to decrypt the message. But I dont know how to write that in, my code is below and should be indented as it is.
def caesar(plain_text, shift):
cipherText = ''
for ch in plain_text:
stayInAlphabet = ord(ch) + shift
if ch.islower():
if stayInAlphabet > ord('z'):
stayInAlphabet -= 26
elif stayInAlphabet < ord('a'):
stayInAlphabet += 26
elif ch.isupper():
if stayInAlphabet > ord('Z'):
stayInAlphabet -= 26
elif stayInAlphabet < ord('A'):
stayInAlphabet += 26
finalLetter = chr(stayInAlphabet)
cipherText += finalLetter
print(cipherText)
return cipherText


selection = input("Would you like to decrypt or encrypt a message? Please enter 'E' or 'D': ")
if selection == 'encrypt':
Cipher = input("Enter text to Cipher: ")
offset = (int(input("Please enter your offset: "))) % 26
caesar(Cipher, offset)

else:
Cipher = input("What is your Cipher? ")
offset = ((int(input("What is your offset? "))) % 26) * -1
caesar(Cipher, offset)
Reply 1
Ok, so it did not indent but here is a picture.2018-01-13.png
Could you explain which part of this you're stuck on?

Also, if you need to post example code, then I'd strongly suggest pasting it into somewhere like https://pyfiddle.io because this forum is poor at preserving formatting and indentation unfortunately!

The code you've pasted looks like it just handles the Caesar cypher and not a Keyword cypher, so here's a wiki page which explains how a Keyword cypher works: https://en.wikipedia.org/wiki/Keyword_cipher

The Wikipedia page uses an example keyword of KRYPTOS, and has a substitution table which looks like:


A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

K R Y P T O S A B C D E F G H I J L M N Q U V W X Z

Perhaps you could use a string in Python to help simplify your algorithm, similar to these above, to help you find substitute letters.

For example:

substitutions = "KRYPTOSABCDEFGHIJLMNQUVWXZ"
position = ord('M') - ord('A') # Position for 'M' in the substitutions string

# Get the substitute character for 'M'
substitute = substitutions[position]


Or reverting back to the original:

substitutions = "KRYPTOSABCDEFGHIJLMNQUVWXZ"
position = substitutions.find('J') # Find character 'J'

# Get the original character from 'J'
theOriginal = chr(ord('A') + position)


Remember that the Keyword cypher relies on the uniqueness of each character in the keyword, so If you need to read the keyword from the user, then I'd suggest you also validate that it doesn't contain any duplicate characters.

Good luck!
(edited 6 years ago)

Quick Reply

Latest