凯撒加密py不用定义函数
时间: 2025-04-23 09:03:43 浏览: 13
凯撒加密是一种简单的替换加密技术,其中每个字母都被替换成它在字母表中固定距离后的另一个字母。这个固定的位移量被称为密钥。下面是一个不需要定义额外函数的Python代码示例来进行凯撒加密:
```python
plaintext = input("请输入明文:")
shift = int(input("请输入偏移值(1-25):"))
# 确保输入的是有效范围内的整数
if not (0 <= shift < 26):
print('错误:偏移值应在1到25之间')
else:
ciphertext = ''
for char in plaintext:
if 'a' <= char <= 'z':
# 小写字母处理
offset = ord(char) - ord('a') + shift
new_char = chr((offset % 26) + ord('a'))
ciphertext += new_char
elif 'A' <= char <= 'Z':
# 大写字母处理
offset = ord(char) - ord('A') + shift
new_char = chr((offset % 26) + ord('A'))
ciphertext += new_char
else:
# 非字母字符保持不变
ciphertext += char
print(f"加密后的文本为:\n{ciphertext}")
```
此程序直接将用户提供的消息按指定数量的位置向右移动,并输出转换过的结果。
阅读全文
相关推荐


















