用python实现凯撒密码与其解密过程。要求:由用户输入明文和位移量
时间: 2024-05-07 11:15:12 浏览: 9
加密过程:
```python
plain_text = input("请输入明文:")
shift = int(input("请输入位移量:"))
# 将明文转换为数字,A对应0,B对应1,以此类推
num_list = [ord(char) - 65 for char in plain_text.upper()]
# 加密
cipher_list = [(num + shift) % 26 for num in num_list]
# 将加密后的数字转换为字符
cipher_text = ''.join([chr(num + 65) for num in cipher_list])
print("加密结果为:", cipher_text)
```
解密过程:
```python
cipher_text = input("请输入密文:")
shift = int(input("请输入位移量:"))
# 将密文转换为数字,A对应0,B对应1,以此类推
num_list = [ord(char) - 65 for char in cipher_text.upper()]
# 解密
plain_list = [(num - shift) % 26 for num in num_list]
# 将解密后的数字转换为字符
plain_text = ''.join([chr(num + 65) for num in plain_list])
print("解密结果为:", plain_text)
```
相关问题
用python实现凯撒密码。要求:由用户输入明文和位移量
,输出密文。
代码如下:
```python
plaintext = input("请输入明文:")
shift = int(input("请输入位移量:"))
ciphertext = ""
for i in plaintext:
if i.isalpha():
if i.isupper():
ciphertext += chr((ord(i) - 65 + shift) % 26 + 65)
else:
ciphertext += chr((ord(i) - 97 + shift) % 26 + 97)
else:
ciphertext += i
print("密文为:", ciphertext)
```
代码解析:
首先,我们从用户输入中获取明文和位移量,分别赋值给`plaintext`和`shift`变量。
然后,我们定义一个空字符串`ciphertext`来存储密文。
接下来,我们遍历明文中的每个字符。如果该字符是字母,我们就对其进行加密操作。如果该字符是大写字母,我们将其转换为ASCII码并减去65,再加上位移量,最后对26取余并加上65,得到密文中对应的字符。如果该字符是小写字母,我们将其转换为ASCII码并减去97,再加上位移量,最后对26取余并加上97,得到密文中对应的字符。如果该字符不是字母,我们直接将其加入到密文中。
最后,我们输出密文。
例如,当用户输入明文为"hello world",位移量为3时,程序会输出密文为"khoor zruog"。
用Python实现凯撒密码。要求:1.由用户输入明文和位移量 2.可以进行解密操作
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 23 15:05:56 2021
@author: OpenAI
"""
def caesar_cipher(text, shift):
cipher_text = ""
for char in text:
if char.isalpha():
ascii_code = ord(char)
shift_code = ascii_code + shift
if char.isupper():
if shift_code > ord('Z'):
shift_code -= 26
elif shift_code < ord('A'):
shift_code += 26
elif char.islower():
if shift_code > ord('z'):
shift_code -= 26
elif shift_code < ord('a'):
shift_code += 26
cipher_text += chr(shift_code)
else:
cipher_text += char
return cipher_text
def main():
text = input("请输入明文:")
shift = int(input("请输入位移量:"))
cipher_text = caesar_cipher(text, shift)
print("加密后的密文为:", cipher_text)
decrypt_text = caesar_cipher(cipher_text, -shift)
print("解密后的明文为:", decrypt_text)
if __name__ == "__main__":
main()