I was looking through the "beginner projects" looking for a way to use dictionaries so I could understand them better. I saw the caesar cipher suggestion and decided to run with that. I created a working one, but (as I saw in the "If...else") just because something works doesn't mean it uses good techniques and is efficient. I saw that Jeff's code was much better--I like the use of dictionaries. So, here's my program. I'd love for you to point out all the bad things about it and help me improve the code (and my techniques).
alphabet = "abcdefghijklmnopqrstuvwxyz"
def encode(words):
encode = {'a':'n', 'b':'o', 'c':'p', 'd':'q', 'e':'r', 'f':'s', 'g':'t', 'h':'u', 'i':'v', 'j':'w', 'k':'x', 'l':'y', 'm':'z', 'n':'a', 'o':'b', 'p':'c', 'q':'d', 'r':'e', 's':'f', 't':'g', 'u':'h', 'v':'i', 'w':'j', 'x':'k', 'y':'l', 'z':'m'}
new_words = ""
for letter in words:
if letter in alphabet:
new_words = new_words + encode[letter]
continue
new_words = new_words + letter
return new_words
def decode(words):
decode = {'n':'a', 'o':'b', 'p':'c', 'q':'d', 'r':'e', 's':'f', 't':'g', 'u':'h', 'v':'i', 'w':'j', 'x':'k', 'y':'l', 'z':'m', 'a':'n', 'b':'o', 'c':'p', 'd':'q', 'e':'r', 'f':'s', 'g':'t', 'h':'u', 'i':'v', 'j':'w', 'k':'x', 'l':'y', 'm':'z'}
new_words = ""
for letter in words:
if letter in alphabet:
new_words = new_words + decode[letter]
continue
new_words = new_words + letter
return new_words
menu = """
(1) Encode
(2) Decode
(3) What's ROT-13?
(4) Quit
"""
choice = 0
end = 0
print "Welcome to Mouche's ROT-13 Encoder/Decoder"
while end != 1:
str1 = ""
str2 = ""
print menu
while choice < 1 or choice > 4:
choice = raw_input("What would you like to do? ")
try:
choice = int(choice)
except ValueError:
print "Please choose an option on the menu (number)."
if choice == 1 or choice == 2:
str1 = raw_input("Message: ").lower()
if choice == 1:
str2 = encode(str1)
print "This is your message after being encoded."
print str2
raw_input("Enter to continue")
if choice == 2:
str2 = decode(str1)
print "This is your message after being decoded."
print str2
raw_input("Enter to continue")
if choice == 3:
print "\nROT-13 is a common caesar cipher. It is encoded by rotating the letters in a message 13 places. Ex: the letter 'a' would be 'n'"
raw_input("Enter to continue")
if choice == 4:
print "Thanks for using Mouche's ROT-13 Encoder/Decoder."
end = 1
choice = 0
Thanks.