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

Python凯撒密码解密函数异常排查:小写字母解密失效但大写字母正常

凯撒密码解密函数小写字母问题排查与修复

嘿,我瞅了你的代码,发现问题出在没有区分大写和小写字母的循环边界上!咱们来拆解一下:

问题根源

你的代码里,只针对「解密后字符小于大写A(65)」的情况做了循环处理,但完全没考虑小写字母的特殊情况——当小写字母解密后落在「大写Z(90)到小写a(97)」之间时(比如小写a减13得到84,也就是大写T),代码直接输出了这个大写字符,而没有把它拉回小写字母的范围(84+26=110,也就是小写n)。

另外你那个第二个elif条件完全是多余的:

elif ((ord(encrpMsg[i]) - decrpKey) < 97 and ((ord(encrpMsg[i]) - decrpKey) > 90)):
    temp = (ord(encrpMsg[i]))
    decryptedMessage += chr(temp)

这个条件判断的是解密后字符在91-96之间(非字母符号),但正常凯撒加密的消息里不会出现这种情况,反而会干扰小写字母的处理逻辑。

修复后的代码

我们可以先判断字符是大写、小写还是空格/其他,然后分别处理循环逻辑:

def decrypt(): 
    print("Here's our Caesar Cipher Decryption program.")
    encrpMsg = input("Enter the message you would like to decrypt: ").strip()
    print()
    decrpKey = int(input("Enter key to decrypt, a number 0-25: "))
    decryptedMessage = ""
    for char in encrpMsg:
        if char == " ":
            decryptedMessage += char
        elif char.isupper():
            # 处理大写字母:解密后小于A则加26循环
            decrypted_char_ord = ord(char) - decrpKey
            if decrypted_char_ord < ord('A'):
                decrypted_char_ord += 26
            decryptedMessage += chr(decrypted_char_ord)
        elif char.islower():
            # 处理小写字母:解密后小于a则加26循环
            decrypted_char_ord = ord(char) - decrpKey
            if decrypted_char_ord < ord('a'):
                decrypted_char_ord += 26
            decryptedMessage += chr(decrypted_char_ord)
        else:
            # 非字母非空格的字符直接保留(按需调整)
            decryptedMessage += char
    print(decryptedMessage)

修复说明

  1. 用char.isupper()和char.islower()替代硬编码的ASCII值,代码更易读也更健壮。
  2. 对大写和小写字母分别设置循环边界:
    • 大写字母解密后如果小于A,就加26回到大写字母范围。
    • 小写字母解密后如果小于a,就加26回到小写字母范围。
  3. 去掉了多余的非字母区间判断,用else灵活处理其他字符(不需要的话可以直接删掉这个分支)。

现在你再用密钥13测试,就能得到预期的全字母输出啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 09:37:43