Python/ciphers/caesar_cipher.py

46 lines
1.2 KiB
Python
Raw Normal View History

from __future__ import print_function
2016-07-29 07:00:38 +00:00
# The Caesar Cipher Algorithm
2016-08-02 17:46:55 +00:00
def main():
message = input("Enter message: ")
2016-11-09 14:17:04 +00:00
key = int(input("Key [1-26]: "))
mode = input("Encrypt or Decrypt [e/d]: ")
2016-08-02 17:46:55 +00:00
if mode.lower().startswith('e'):
mode = "encrypt"
elif mode.lower().startswith('d'):
mode = "decrypt"
translated = encdec(message, key, mode)
2016-11-09 14:17:04 +00:00
if mode == "encrypt":
print(("Encryption:", translated))
2016-08-02 17:46:55 +00:00
elif mode == "decrypt":
print(("Decryption:", translated))
2016-08-02 17:46:55 +00:00
def encdec(message, key, mode):
2016-11-09 14:17:04 +00:00
message = message.upper()
2016-08-02 17:46:55 +00:00
translated = ""
2016-11-09 14:17:04 +00:00
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2016-08-02 17:46:55 +00:00
for symbol in message:
if symbol in LETTERS:
num = LETTERS.find(symbol)
2016-11-09 14:17:04 +00:00
if mode == "encrypt":
2016-08-02 17:46:55 +00:00
num = num + key
elif mode == "decrypt":
num = num - key
if num >= len(LETTERS):
2016-11-09 14:17:04 +00:00
num -= len(LETTERS)
2016-08-02 17:46:55 +00:00
elif num < 0:
2016-11-09 14:17:04 +00:00
num += len(LETTERS)
2016-08-02 17:46:55 +00:00
2016-11-09 14:17:04 +00:00
translated += LETTERS[num]
2016-08-02 17:46:55 +00:00
else:
2016-11-09 14:17:04 +00:00
translated += symbol
2016-08-02 17:46:55 +00:00
return translated
if __name__ == '__main__':
import doctest
doctest.testmod()
2016-11-09 14:17:04 +00:00
main()