patternpythonModerate
Caesar cipher in Python
Viewed 0 times
caesarpythoncipher
Problem
I wrote this looping Caesar cipher with a default key. I'd love for some input on how I could make this operate better/more effectively.
#Et Tu, Brute? [Caesar's Cipher]
#loops?
#Determine type of cipher...
doLoop=("y")
while doLoop==("y"):
#yep. loops.
det=input("Enter N for number or C for character; 'exit' to quit program ").lower() #lower case for simplicity! it don't care!
#Now the fun part!
#Numbers...
if (det)==("n"):
print("The default cipher key is 5")
numRaw=input("Enter number to be decoded: ")
if ord(numRaw)<ord("5"):
numDec=ord(numRaw)+5
else:
numDec=ord(numRaw)-5
print("The decoded number is: ",(chr(numDec)))
#Letters...
if (det)==("c"):
print("The default cipher key is 13")
charRaw=input("Enter character to be decoded: ").lower() #lower case for simplicity!
if ord(charRaw)<ord("m"):
charDec=ord(charRaw)+13
else:
charDec=ord(charRaw)-13
print("The decoded character is: " , (chr(charDec)))
if det==("exit"):
breakSolution
Python strings have a
of coarse in python2(with a shift of 13) one can simply do
translate method that applies a substitution cipher. There is also a function str.maketrans (string.maketrans in Python 2) that helps with building the translation table:>>> from string import ascii_lowercase as alphabet
>>> shift = 13
>>> cipher = str.maketrans(alphabet, alphabet[shift:] + alphabet[:shift])
>>> print("caeser salad is tasty".translate(cipher))
pnrfre fnynq vf gnfglof coarse in python2(with a shift of 13) one can simply do
"My Message".encode("rot13")Code Snippets
>>> from string import ascii_lowercase as alphabet
>>> shift = 13
>>> cipher = str.maketrans(alphabet, alphabet[shift:] + alphabet[:shift])
>>> print("caeser salad is tasty".translate(cipher))
pnrfre fnynq vf gnfglContext
StackExchange Code Review Q#32694, answer score: 15
Revisions (0)
No revisions yet.