You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为什么我编写的Python凯撒密码加密结果偏移1个字符?

凯撒密码代码问题排查

核心问题原因

你遇到的{变成a的问题,根源是你写的偏移回绕逻辑不符合需求:

  • 小写字母w的ASCII值为119,按你测试用的偏移值4计算,119+4=123,刚好是{的ASCII值,符合你的预期输出。
  • 但你的代码中加了判断:只要偏移后的ASCII值大于ord('z')(也就是122),就按小写字母回绕规则重新计算值,123满足这个判断条件,会触发计算:
    cipherValue = ord('a') + 4 - (ord('z') - 119 +1) = 97 +4 -4 =97
    
    97就是小写字母a的ASCII值,直接导致结果出错。

其他隐藏问题

你的代码没有定义message变量,缺少读取用户输入待加密文本的逻辑,运行时会直接报错。

修正方案

如果你当前的练习要求是所有ASCII字符直接叠加偏移值,不需要对字母做循环回绕,直接删除多余的回绕判断即可,修正后代码如下:

distance = int(input("Enter the distance value: "))
# 补充读取明文的逻辑
message = input("Enter the message to encrypt: ")
code = ""
for ch in message:
    ordvalue = ord(ch)
    cipherValue = ordvalue + distance
    code += chr(cipherValue)
print(code)

如果后续要求改为仅对大小写字母做循环回绕、其他字符正常叠加偏移,可以用下面的版本:

distance = int(input("Enter the distance value: "))
message = input("Enter the message to encrypt: ")
code = ""
for ch in message:
    ordvalue = ord(ch)
    cipherValue = ordvalue + distance
    # 小写字母回绕逻辑
    if 'a' <= ch <= 'z':
        if cipherValue > ord('z'):
            cipherValue -= 26
    # 大写字母回绕逻辑
    elif 'A' <= ch <= 'Z':
        if cipherValue > ord('Z'):
            cipherValue -= 26
    code += chr(cipherValue)
print(code)

内容的提问来源于stack exchange,提问作者Aces Radix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 23:39:00