Skip to content

Instantly share code, notes, and snippets.

@carrickkv2
Created September 2, 2022 23:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carrickkv2/4475112112c7da6248282b57f2c07163 to your computer and use it in GitHub Desktop.
Save carrickkv2/4475112112c7da6248282b57f2c07163 to your computer and use it in GitHub Desktop.
Encrypts or decrypts a message using the caesar cipher algorithm.
import string
list_of_alphabets_and_digits = [
string.ascii_lowercase,
string.ascii_uppercase,
string.digits,
]
def shift(alphabets_and_digits_to_shift: str, key_to_shift_by: int) -> str:
"""
Shift any digits and alphabets that are passed in.
"""
return (
alphabets_and_digits_to_shift[key_to_shift_by:]
+ alphabets_and_digits_to_shift[:key_to_shift_by]
)
def encrypt_or_decrypt_text(
message: str, key: int, alphabets_and_digits: list[str], decrypt_or_encrypt: bool
) -> str:
"""
This function encrypts or decrypts a text that has been passed in
and returns the encrypted / decrypted text.
"""
shifted_alphabets_and_digits = [
shift(value, key) for value in alphabets_and_digits
] # Call the shift function with alphabets_and_digits using a list comprehension
# turn characters in the list into a string
joined_alphabets_and_digits = "".join(alphabets_and_digits)
joined_shifted_alphabets_and_digits = "".join(shifted_alphabets_and_digits)
if decrypt_or_encrypt is True:
mapping_table = str.maketrans(
joined_alphabets_and_digits, joined_shifted_alphabets_and_digits
) # Create a mapping table
else:
mapping_table = str.maketrans(
joined_shifted_alphabets_and_digits, joined_alphabets_and_digits
)
return message.translate(
mapping_table
) # Use the mapping table to replace characters in
# the original message with the shifted characters
print("Heya. Welcome to the Caesar Cipher Program\n")
choose_decryption_or_encryption = input(
"Please type yes if you'll like to like encrypt a message or no if you'll like to decrypt a message: \n"
).lower()
choose_decryption_or_encryption = (
True if choose_decryption_or_encryption == "yes" else False
)
message = input("\nPlease type the message you'll like to encrypt_or_decrypt\n")
key = int(
input(
"\nPlease type the key you'll like to encrypt_or_decrypt the message with.\n"
"This should be a positive integer between the range of 0 to 25. \n"
)
)
if __name__ == "__main__":
print(f"\n{encrypt_or_decrypt_text(message, key, list_of_alphabets_and_digits, choose_decryption_or_encryption)}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment