用下标方法,写出凯撒密码的python加密与解密的代码,位移值为K,用户能自己输入K和明文或密文,并写出输入与输出
时间: 2023-05-28 21:04:17 浏览: 43
加密代码:
```python
# 输入明文和位移值K
plaintext = input("请输入明文:")
K = int(input("请输入位移值K:"))
# 将明文转换为小写字母
plaintext = plaintext.lower()
# 加密明文
ciphertext = ""
for i in range(len(plaintext)):
if plaintext[i] >= 'a' and plaintext[i] <= 'z':
ciphertext += chr((ord(plaintext[i]) - 97 + K) % 26 + 97)
else:
ciphertext += plaintext[i]
# 输出密文
print("加密后的密文为:", ciphertext)
```
解密代码:
```python
# 输入密文和位移值K
ciphertext = input("请输入密文:")
K = int(input("请输入位移值K:"))
# 将密文转换为小写字母
ciphertext = ciphertext.lower()
# 解密密文
plaintext = ""
for i in range(len(ciphertext)):
if ciphertext[i] >= 'a' and ciphertext[i] <= 'z':
plaintext += chr((ord(ciphertext[i]) - 97 - K) % 26 + 97)
else:
plaintext += ciphertext[i]
# 输出明文
print("解密后的明文为:", plaintext)
```
输入输出示例:
```
请输入明文:hello world
请输入位移值K:3
加密后的密文为: khoor zruog
请输入密文:khoor zruog
请输入位移值K:3
解密后的明文为: hello world
```