Sure! Here are the answers and the activity:
-
Improvements: We could make the program so that each letter gets a different encrypted letter every time (like a random substitution).
-
Challenges: Coding for random substitutions can be tough because it’s tricky to keep track of which letter was changed to which. It might also mess up the decryption process.
-
Testing Awareness: You always gotta check if the output is correct because if it isn’t, you’ll get unexpected results. Like if you order a pizza and get a salad instead, that's not what you wanted!
Activity Code:
Here’s a simple function that can either encrypt or decrypt a message:
import random
def encrypt(message, key):
ciphertext = ""
for x in message:
number = ord(x)
number = number - ord('A')
number = (number + key) % 26
number = number + ord('A')
letter = chr(number)
ciphertext += letter
return ciphertext
def decrypt(ciphertext, key):
plaintext = ""
for x in ciphertext:
number = ord(x)
number = number - ord('A')
number = (number - key) % 26
number = number + ord('A')
letter = chr(number)
plaintext += letter
return plaintext
key = random.randint(1, 25) # Random key between 1 and 25
message = "ZEBRA"
encrypted_message = encrypt(message, key)
decrypted_message = decrypt(encrypted_message, key)
print(f"Encrypted: {encrypted_message}")
print(f"Decrypted: {decrypted_message}")
This code generates a random key for the encryption and decryption process!