Created
October 27, 2015 08:37
-
-
Save mahanmarwat/d86a5b35b97750f2b875 to your computer and use it in GitHub Desktop.
Caesar Cipher with key support.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Substitution cypher, Ceasar's Cipher""" | |
from __future__ import print_function | |
import sys | |
MIN = 97 | |
MAX = 122 | |
def encode(text, n): | |
"""Encode the text. | |
:text: the text to be encoded | |
:n: the key, to rotate the text that number of time | |
""" | |
encoded_text = '' | |
for i in text.lower(): | |
if i.isalpha(): | |
encoded_char = ord(i) | |
for i in range(n): | |
if encoded_char == MAX: | |
encoded_char = MIN | |
else: | |
encoded_char += 1 | |
encoded_text += chr(encoded_char) | |
else: | |
encoded_text += i | |
return encoded_text | |
def decode(text, n): | |
"""Decode the text. | |
:text: the text to be decoded | |
:n: the key, to rotate the text that number of time | |
""" | |
decoded_text = '' | |
for i in text.lower(): | |
if i.isalpha(): | |
decoded_char = ord(i) | |
for i in range(n): | |
if decoded_char == MIN: | |
decoded_char = MAX | |
else: | |
decoded_char -= 1 | |
decoded_text += chr(decoded_char) | |
else: | |
decoded_text += i | |
return decoded_text | |
if __name__ == '__main__': | |
get_input = input | |
if sys.version_info[:2] <= (2, 7): | |
get_input = raw_input | |
while True: | |
encode_or_decode = get_input('Enter "E" for encoding or "D" for decoding or "Q" for Quit: ').lower() | |
if encode_or_decode == 'q': | |
break | |
if encode_or_decode not in ('e', 'd'): | |
continue | |
text = get_input('Enter text: ').lower() | |
while not text: | |
text = get_input('Please enter some text: ').lower() | |
while True: | |
key = get_input('Enter key (positive number): ') | |
try: | |
key = int(key) | |
except ValueError: | |
continue | |
else: | |
break | |
if encode_or_decode == 'e': | |
print(encode(text, key)) | |
elif encode_or_decode == 'd': | |
print(decode(text, key)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment