Last active
December 10, 2017 03:13
-
-
Save chaewonkong/ea4a00ffabf3008eae142673c8702f01 to your computer and use it in GitHub Desktop.
Caesar Cypher Encoder/Decoder
This file contains hidden or 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
| '''Caesar Cypher encoder/decoder | |
| From input, this program will generate Caesar cypher(each alphabets of input will be changed 3 step forward alphabets | |
| in alphabet order. It will print the outcome. | |
| Then, the program will decode the generated Caesar cypher and print it. | |
| The user can compare her/his original input to the printed outcome. | |
| ''' | |
| import string | |
| #We will not change digits, whitespaces or punctuations. Those will remain the same. | |
| LOWER = string.ascii_lowercase | |
| SKIP = string.digits + string.whitespace + string.punctuation | |
| #Function that encodes plain text to cypher. It changes any kinds of alphabet 3 stepts forward('A' will become 'D') | |
| #About X, Y, Z, x, y, z, X will become 'A' and z will become 'c'.(uppercase alphabet loop for uppercase, lower for lower) | |
| def caesar_cipher_encode(plain_text: str, step=3): | |
| cipher = '' | |
| for c in plain_text: | |
| if c in SKIP: #punctuations, whitespaces, digits | |
| cipher += c | |
| continue | |
| diff = ord(c) - (ord('a') if c in LOWER else ord('A')) | |
| #For last three characters in alphabet order: | |
| diff = (diff + step) % 26 | |
| cipher += chr(diff + (ord('a') if c in LOWER else ord('A'))) | |
| return cipher | |
| #Get an input of a string from the user. | |
| strInput = input("Please enter a string: ") | |
| #Encode the input and print it | |
| encode = caesar_cipher_encode(strInput) | |
| print(encode) | |
| #Decode the cypher(which is encoded input) and print it. | |
| #What we have to do is just changing step=3 to step=-3 | |
| decode = caesar_cipher_encode(encode, step=-3) | |
| print(decode) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment