patternpythonMinor
A Simple Caesar Cipher in Python
Viewed 0 times
caesarsimplepythoncipher
Problem
I wrote an encryption/decryption algorithm for the Caesar Cipher. It works fine, but I'm curious if there are any constructive critiques, tips, tricks, comments, or advice anyone may have on how the code operates, performs, looks, etc.
```
# Caesar Cipher
def chooseMode():
while True:
mode = raw_input("\nChoose a mode (encryption or decryption):\n 1) Encrypt \n 2) Decrypt\n 3) Brute Force\n\n")
if mode in ['1', '2', '3']:
return mode
def collectMessage():
message = raw_input("Enter the message you would like to translate:\n\n")
return message
def collectKey():
while True:
key = raw_input("What is the key for your message? (Enter a number from 0 to 26): \n")
try:
if int(key) in range(27):
return int(key)
else:
print("Please enter an integer between 0 and 26.\n")
continue
except ValueError:
print("Please enter an integer between 0 and 26.\n")
continue
def translateMessage(text, cipher_mode, caeser_key):
translation = ''
# If decrypting, convert key to negative.
if cipher_mode == '2':
caeser_key = -caeser_key
for symbol in text:
# Convert only Alphabetical Symbols
if symbol.isalpha():
num = ord(symbol)
# Shift num down to 1 through 26 for more easier to visualize modulous.
# Then Apply the Key; then Modulate; then Move Back Up; then Build into Chr and Translation
if symbol.isupper():
num -= ord('A')
num += caeser_key
num %= 26
num += ord('A')
translation += chr(num)
else:
num -= ord('a')
num -= caeser_key
num %= 26
num += ord('a')
translation += chr(num)
else:
translation += symbol
return translation
def bruteForce(text,
```
# Caesar Cipher
def chooseMode():
while True:
mode = raw_input("\nChoose a mode (encryption or decryption):\n 1) Encrypt \n 2) Decrypt\n 3) Brute Force\n\n")
if mode in ['1', '2', '3']:
return mode
def collectMessage():
message = raw_input("Enter the message you would like to translate:\n\n")
return message
def collectKey():
while True:
key = raw_input("What is the key for your message? (Enter a number from 0 to 26): \n")
try:
if int(key) in range(27):
return int(key)
else:
print("Please enter an integer between 0 and 26.\n")
continue
except ValueError:
print("Please enter an integer between 0 and 26.\n")
continue
def translateMessage(text, cipher_mode, caeser_key):
translation = ''
# If decrypting, convert key to negative.
if cipher_mode == '2':
caeser_key = -caeser_key
for symbol in text:
# Convert only Alphabetical Symbols
if symbol.isalpha():
num = ord(symbol)
# Shift num down to 1 through 26 for more easier to visualize modulous.
# Then Apply the Key; then Modulate; then Move Back Up; then Build into Chr and Translation
if symbol.isupper():
num -= ord('A')
num += caeser_key
num %= 26
num += ord('A')
translation += chr(num)
else:
num -= ord('a')
num -= caeser_key
num %= 26
num += ord('a')
translation += chr(num)
else:
translation += symbol
return translation
def bruteForce(text,
Solution
Some style notes (you can read more 'bout them on Python's official style-guide which is called PEP8):
-
instead of commenting lines at the middle of the method, just add a docstring:
About the code
About the algorithm
-
In Python, we have the
Which outputs:
-
Another built-in that you may take advantage of is:
PS: You can also have a quick look at this answer for other recommendations that might apply quite well to your code.
- you misspelled Caeser. It should be Caesar.
- function names should be snake_cased not camelCased
-
instead of commenting lines at the middle of the method, just add a docstring:
def choose_mode():
"""
Docstring here
"""
# the rest of your code- you should add the
if __name__ == '__main__'guard
About the code
- It's pretty weird to use
exitwhich is a helper for the interactive shell instead ofsys.exitwhich is intended for use in programs. I'd stick to the latter.
- In
collectMessage()you can directly returnraw_input("Enter the message you would like to translate:\n\n")
- In
collectKey():you can remove bothcontinuestatements
- You should use
format()when printing. Here, you can read more about formatting.
About the algorithm
-
In Python, we have the
translate method which applies a substitution cipher to a string. More, when building the translation table, in Python 2, we have string.maketrans.import string
from string import ascii_lowercase
shift = 6
cipher = string.maketrans(ascii_lowercase, ascii_lowercase[shift:] + ascii_lowercase[:shift])
print "I love to review code at midnight because I have no life".translate(cipher)Which outputs:
I rubk zu xkbokc iujk gz sojtomnz hkigayk I ngbk tu rolk-
Another built-in that you may take advantage of is:
"I love to review code at midnight because I have no life".encode("rot13")PS: You can also have a quick look at this answer for other recommendations that might apply quite well to your code.
Code Snippets
def choose_mode():
"""
Docstring here
"""
# the rest of your codeimport string
from string import ascii_lowercase
shift = 6
cipher = string.maketrans(ascii_lowercase, ascii_lowercase[shift:] + ascii_lowercase[:shift])
print "I love to review code at midnight because I have no life".translate(cipher)"I love to review code at midnight because I have no life".encode("rot13")Context
StackExchange Code Review Q#157855, answer score: 6
Revisions (0)
No revisions yet.