Professional Documents
Culture Documents
Writing Caesar Cipher Program by Using Function in Python Programming
Writing Caesar Cipher Program by Using Function in Python Programming
Writing Caesar Cipher Program by Using Function in Python Programming
Certainly! I can help you write a Caesar cipher program using functions in Python. The Caesar cipher is a
simple substitution cipher where each letter in the plaintext is shifted a certain number of positions
down or up the alphabet.
pythonCopy code
def encrypt(plaintext, shift): ciphertext = "" for char in plaintext: if char.isalpha(): if char.isupper():
ciphertext += chr((ord(char) - ord('A') + shift) % 26 + ord('A')) else: ciphertext += chr((ord(char) - ord('a')
+ shift) % 26 + ord('a')) else: ciphertext += char return ciphertext def decrypt(ciphertext, shift): return
encrypt(ciphertext, -shift) # Test the functions plaintext = "Hello, World!" shift = 3 encrypted_text =
encrypt(plaintext, shift) print("Encrypted text:", encrypted_text) decrypted_text =
decrypt(encrypted_text, shift) print("Decrypted text:", decrypted_text)
In this example, we have two functions: encrypt() and decrypt(). The encrypt() function takes a plaintext
and a shift value as input and returns the corresponding ciphertext. The decrypt() function is
implemented using the encrypt() function by providing a negative shift value.
The encrypt() function iterates over each character in the plaintext. If the character is alphabetic, it
checks if it is uppercase or lowercase and applies the shift accordingly using the ASCII values. If the
character is not alphabetic, it is added to the ciphertext without any modification.
Finally, we test the functions by encrypting the plaintext "Hello, World!" with a shift of 3, and then
decrypting the ciphertext using the same shift. The output will be:
arduinoCopy code
Feel free to modify the code to suit your needs or add additional functionality as desired.