-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathcesar.py
79 lines (64 loc) · 1.86 KB
/
cesar.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# Define the alphabet
alphabet = "abcdefghijklmnopqrstuvwxyz"
# Function to encrypt a message
def encrypt(message, key):
"""
Encrypts a message using the Caesar cipher.
Args:
message: The message to encrypt.
key: The key for the cipher.
Returns:
The encrypted message.
"""
encrypted_message = ""
for letter in message:
# Get the position of the letter in the alphabet
letter_position = alphabet.find(letter)
# Apply the key
new_position = letter_position + key
# Get the new letter
new_letter = alphabet[new_position % len(alphabet)]
# Add the new letter to the encrypted message
encrypted_message += new_letter
return encrypted_message
# Function to decrypt a message
def decrypt(message, key):
"""
Decrypts a message using the Caesar cipher.
Args:
message: The message to decrypt.
key: The key for the cipher.
Returns:
The decrypted message.
"""
decrypted_message = ""
for letter in message:
# Get the position of the letter in the alphabet
letter_position = alphabet.find(letter)
# Apply the inverse key
new_position = letter_position - key
# Get the new letter
new_letter = alphabet[new_position % len(alphabet)]
# Add the new letter to the decrypted message
decrypted_message += new_letter
return decrypted_message
# Program options
options = {
"encrypt": encrypt,
"decrypt": decrypt
}
# Get the user's desired option
option = input("What do you want to do? (encrypt/decrypt): ")
# If the option is valid
if option in options:
# Get the message from the user
message = input("Enter the message: ")
# Get the key from the user
key = int(input("Enter the key: "))
# Apply the desired option
message_result = options[option](message, key)
# Print the result
print("Result:", message_result)
# If the option is not valid
else:
print("Invalid option.")