Last active
February 11, 2018 10:38
-
-
Save tmitzka/2d139cd349fc0886ca0fd81902105cb3 to your computer and use it in GitHub Desktop.
Encrypts a message using a Caesar cipher.
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
#!/usr/bin/env python3 | |
"""Encrypts a message using a Caesar cipher. | |
https://en.wikipedia.org/wiki/Caesar_cipher | |
""" | |
from string import ascii_uppercase | |
class Caesar(): | |
def __init__(self, shift): | |
self.shift = shift | |
self.letters = ascii_uppercase | |
def __repr__(self): | |
return "Performs a Caesar encryption." | |
def get_message(self): | |
print("Enter message:") | |
message = input().upper() | |
return message | |
def encrypt(self, message): | |
cipher = "" | |
# Special characters don't get encrypted. | |
# find() returns -1 if a string is not contained | |
# in the letters from A-Z. | |
for character in message: | |
index = self.letters.find(character) | |
if index == -1: | |
cipher += character | |
else: | |
cipher_index = index + shift | |
# After Z, start again from A: | |
if cipher_index > 25: | |
cipher_index -= 26 | |
cipher += self.letters[cipher_index] | |
return cipher | |
# Set cipher shift (max. 25). | |
shift = 3 | |
c = Caesar(shift) | |
message = c.get_message() | |
cipher = c.encrypt(message) | |
print("\nEncrypted message:") | |
print(cipher) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment