在Python中实现凯撒密码,你可以使用以下代码:
def caesar_encrypt(text, shift):encrypted_text = ""for char in text:if char.isalpha():将字符转换为大写char = char.upper()计算字符移动后的位置shifted = (ord(char) - ord('A') + shift) % 26将移动后的字符添加到加密文本中encrypted_text += chr(shifted + ord('A'))else:非字母字符保持不变encrypted_text += charreturn encrypted_textdef caesar_decrypt(text, shift):decrypted_text = ""for char in text:if char.isalpha():将字符转换为大写char = char.upper()计算字符移动前的位置shifted = (ord(char) - ord('A') - shift) % 26将移动前的字符添加到解密文本中decrypted_text += chr(shifted + ord('A'))else:非字母字符保持不变decrypted_text += charreturn decrypted_text[1:] 去掉末尾的空格示例使用plaintext = "Hello, World!"shift = 3encrypted_text = caesar_encrypt(plaintext, shift)print("Encrypted text:", encrypted_text)decrypted_text = caesar_decrypt(encrypted_text, shift)print("Decrypted text:", decrypted_text)
这段代码定义了两个函数:`caesar_encrypt` 和 `caesar_decrypt`,分别用于加密和解密文本。它们都接受一个文本字符串和一个位移量作为参数,并返回加密或解密后的文本。
在加密函数中,如果字符是字母,则将其转换为大写,然后根据位移量计算出加密后的字符,并将其添加到加密文本中。如果字符不是字母,则保持不变。
在解密函数中,过程与加密类似,但是计算方式是减去位移量。
最后,示例代码展示了如何使用这两个函数来加密和解密一段文本。

