Challenge: Implementing Caesar Cipher
Uppgift
Swipe to start coding
Now, we will implement a simple function that provides data encryption using Caesar cipher.
Your task is to:
- Check if the character is alphabetic inside the
for
loop of thecaesar_cipher()
function. Use the.isalpha()
method to do it. - Set the value of the
key
variable equal to3
. - Call the
caesar_cipher()
and specify the required arguments (plaintext
andkey
).
Note
To provide decryption, we can use the same function but with other arguments:
caesar_cipher(encrypted_text, neg_key)
whereneg_key
=- key
.
Lösning
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
def caesar_cipher(text, key):
result = ""
# Loop through each character in the input text
for char in text:
if char.isalpha(): # Check if the character is alphabetic
start = ord('A') if char.isupper() else ord('a') # Set the starting point based on uppercase or lowercase
result += chr((ord(char) - start + key) % 26 + start) # Apply the Caesar cipher formula
else:
result += char # Non-alphabetic characters remain unchanged
return result
# Example Usage:
plaintext = "1WORLD2" # Change the word for encryption
key = 3
encrypted_text = caesar_cipher(plaintext, key)
# Print the results
print(f"Plaintext: {plaintext}")
print(f"Key: {key}")
print(f"Encrypted Text: {encrypted_text}")
Var allt tydligt?
Tack för dina kommentarer!
Avsnitt 3. Kapitel 3
single
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
def caesar_cipher(text, key):
result = ""
# Loop through each character in the input text
for char in text:
if char.___(): # Check if the character is alphabetic
start = ord('A') if char.isupper() else ord('a') # Set the starting point based on uppercase or lowercase
result += chr((ord(char) - start + key) % 26 + start) # Apply the Caesar cipher formula
else:
result += char # Non-alphabetic characters remain unchanged
return result
# Example Usage:
plaintext = "1WORLD2" # Change the word for encryption
key = ___
encrypted_text = caesar_cipher(___, ___)
# Print the results
print(f"Plaintext: {plaintext}")
print(f"Key: {key}")
print(f"Encrypted Text: {encrypted_text}")
Fråga AI
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal