Big Idea 5.4 Safe Computing
Software Development using Frontend and Backend Technologies
Homework Hack 2
import random
def caesar_cipher(text, shift_value, operation):
transformed_text = []
for character in text:
if character.isalpha():
base = ord('A') if character.isupper() else ord('a')
offset = shift_value if operation == "encrypt" else -shift_value
transformed_text.append(chr((ord(character) - base + offset) % 26 + base))
else:
transformed_text.append(character)
return ''.join(transformed_text)
# User input handling
operation = input("Would you like to encrypt or decrypt? ").strip().lower()
text_input = input("Enter your text: ")
shift_value = input("Enter shift value (or type 'random' for a random shift): ").strip().lower()
# Generate a random shift if "random" is entered
if shift_value == "random":
shift_value = random.randint(1, 25)
print(f"Randomly selected shift: {shift_value}")
else:
shift_value = int(shift_value)
# Execute the cipher function
final_output = caesar_cipher(text_input, shift_value, operation)
print(f"Transformed Text: {final_output}")