用python实现凯撒密码。要求:1.由用户输入明文和位移量 2.可以进行解密操作
时间: 2024-06-06 12:11:28 浏览: 13
# Caesar Cipher in Python
# Function to encrypt the plain text
def encrypt(plain_text, shift):
cipher_text = ""
for char in plain_text:
if char.isalpha():
# Shift character by specified number of positions
char_code = ord(char) + shift
if char.isupper():
if char_code > ord('Z'):
char_code -= 26
elif char_code < ord('A'):
char_code += 26
else:
if char_code > ord('z'):
char_code -= 26
elif char_code < ord('a'):
char_code += 26
cipher_text += chr(char_code)
else:
cipher_text += char
return cipher_text
# Function to decrypt the cipher text
def decrypt(cipher_text, shift):
plain_text = ""
for char in cipher_text:
if char.isalpha():
# Shift character by specified number of positions
char_code = ord(char) - shift
if char.isupper():
if char_code > ord('Z'):
char_code -= 26
elif char_code < ord('A'):
char_code += 26
else:
if char_code > ord('z'):
char_code -= 26
elif char_code < ord('a'):
char_code += 26
plain_text += chr(char_code)
else:
plain_text += char
return plain_text
# Get input from user
plain_text = input("Enter the plain text: ")
shift = int(input("Enter the shift value: "))
# Encrypt the plain text
cipher_text = encrypt(plain_text, shift)
print("Cipher text:", cipher_text)
# Decrypt the cipher text
plain_text = decrypt(cipher_text, shift)
print("Plain text:", plain_text)