Skip to content

Update Caesar_cipher.py #379

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 31 additions & 32 deletions Caesar_Cipher/Caesar_cipher.py
Original file line number Diff line number Diff line change
@@ -1,45 +1,44 @@
class main:
def __init__(self,key:dict) -> None:
class CipherTool:
def __init__(self, key: dict) -> None:
self.key = key
self.reverse_key = {v: k for k, v in key.items()}
self.blank_string = ""
self.decrypted_string = ""

def get_input(self) -> None:
def get_input(self) -> None:
while True:
blank_string = str(input("Enter string to decrypt: "))
blank_string = input("Enter string to encrypt (letters only): ")
if blank_string.isalpha():
blank_string = blank_string.lower()
self.blank_string = blank_string
self.blank_string = blank_string.lower()
break
else:
print("Input is not valid")
continue
print("Invalid input. Please enter alphabetic characters only.")

def encrypt_string(self) -> str:
output = ""
for c in self.blank_string:
for k,v in self.key.items():
if k == c:
output += v
else:
continue
output = ''.join(self.key.get(c, c) for c in self.blank_string)
self.decrypted_string = output
return(output)
return output

def decrypt_string(self, string: str) -> str:
output = ""
string = string.lower()
string = string.strip()
if string == "":
return(self.blank_string)
else:
for c in string:
for k,v in self.key.items():
if v == c:
output += k

return(output)
string = string.lower().strip()
if not string:
return self.blank_string
return ''.join(self.reverse_key.get(c, c) for c in string)


if __name__ == "__main__":
key ={"a": "d", "b": "e", "c": "f", "d": "g", "e": "h", "f": "i", "g": "j", "h": "k", "i": "l", "j": "m", "k": "n", "l": "o", "m": "p", "n": "q", "o": "r", "p": "s", "q": "t", "r": "u", "s": "v", "t": "w", "u": "x", "v": "y", "w": "z", "x": "a", "y": "b", "z": "c"}
main = main(key=key)
main.get_input()
print(main.encrypt_string())
key = {
"a": "d", "b": "e", "c": "f", "d": "g", "e": "h", "f": "i",
"g": "j", "h": "k", "i": "l", "j": "m", "k": "n", "l": "o",
"m": "p", "n": "q", "o": "r", "p": "s", "q": "t", "r": "u",
"s": "v", "t": "w", "u": "x", "v": "y", "w": "z", "x": "a",
"y": "b", "z": "c"
}

cipher = CipherTool(key=key)
cipher.get_input()
encrypted = cipher.encrypt_string()
print("Encrypted string:", encrypted)

decrypted = cipher.decrypt_string(encrypted)
print("Decrypted back:", decrypted)