def encrypt(plain_text, shift): encrypted_text = "" for char in plain_text: if char.isalpha(): if char.isupper(): encrypted_text += chr((ord(char) - 65 + shift) % 26 + 65) else: encrypted_text += chr((ord(char) - 97 + shift) % 26 + 97) else: encrypted_text += char return encrypted_text def decrypt(encrypted_text, shift): decrypted_text = "" for char in encrypted_text: if char.isalpha(): if char.isupper(): decrypted_text += chr((ord(char) - 65 - shift) % 26 + 65) else: decrypted_text += chr((ord(char) - 97 - shift) % 26 + 97) else: decrypted_text += char return decrypted_text # 代码输入和输出部分 text = input("输入想要加密或解密的文本:") shift = int(input("输入加密的数位:")) encrypted = encrypt(text, shift) print("加密后的文本:", encrypted) decrypted = decrypt(encrypted, shift) print("解密后的文本:", decrypted)
时间: 2024-04-14 11:29:04 浏览: 118
这是一个改进后的程序,它允许用户输入要加密或解密的文本,并指定加密的位移。
```python
def encrypt(plain_text, shift):
encrypted_text = ""
for char in plain_text:
if char.isalpha():
if char.isupper():
encrypted_text += chr((ord(char) - 65 + shift) % 26 + 65)
else:
encrypted_text += chr((ord(char) - 97 + shift) % 26 + 97)
else:
encrypted_text += char
return encrypted_text
def decrypt(encrypted_text, shift):
decrypted_text = ""
for char in encrypted_text:
if char.isalpha():
if char.isupper():
decrypted_text += chr((ord(char) - 65 - shift) % 26 + 65)
else:
decrypted_text += chr((ord(char) - 97 - shift) % 26 + 97)
else:
decrypted_text += char
return decrypted_text
# 代码输入和输出部分
text = input("输入想要加密或解密的文本:")
shift = int(input("输入加密的数位:"))
encrypted = encrypt(text, shift)
print("加密后的文本:", encrypted)
decrypted = decrypt(encrypted, shift)
print("解密后的文本:", decrypted)
```
现在,您可以输入要加密或解密的文本,并指定一个数字作为加密的位移。程序将输出加密后的文本以及解密后的文本。
阅读全文
相关推荐
















