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

Python凯撒密码加解密功能异常调试求助(高中课程项目)

问题根因
  • 字符处理逻辑未做类型区分:现有加密、解密逻辑仅适配大写英文字母,输入的Hello World!包含小写字母、空格、感叹号三类非大写字母字符,计算xCode - ord("A")时会得到超出0-25区间的数值,移位运算后结果完全不符合预期,是解密结果与原始明文不一致的核心原因。
  • 冗余函数无效:定义的toList函数未被调用,且本身逻辑存在问题——text.split()会返回分割后的列表,但未将结果赋值就直接返回原字符串,函数无实际作用。
修复方案(符合高中项目要求,支持后续扩展)

修复后代码保留函数、循环的实现要求,使用列表存储中间处理结果,新增字符类型判断分支,预留数字、标点的扩展位置:

# 加密函数:默认移位值为3,可自定义调整
def encrypt(text, shift=3):
    encryption_list = []
    for char in text:
        char_code = ord(char)
        # 处理大写字母
        if ord('A') <= char_code <= ord('Z'):
            offset = char_code - ord("A")
            new_offset = (offset + shift) % 26
            encryption_list.append(chr(new_offset + ord("A")))
        # 处理小写字母
        elif ord('a') <= char_code <= ord('z'):
            offset = char_code - ord("a")
            new_offset = (offset + shift) % 26
            encryption_list.append(chr(new_offset + ord("a")))
        # 后续需要加密数字、标点时,在此处新增对应判断分支即可
        # 非目标加密字符默认原样保留
        else:
            encryption_list.append(char)
    encryption_result = ''.join(encryption_list)
    print("加密后文本: ", encryption_result)
    print("原始明文:", text)
    return encryption_result

# 解密函数:与加密逻辑对应
def decrypt(cipher_text, shift=3):
    decrypt_list = []
    for char in cipher_text:
        char_code = ord(char)
        if ord('A') <= char_code <= ord('Z'):
            offset = char_code - ord("A")
            new_offset = (offset - shift) % 26
            decrypt_list.append(chr(new_offset + ord("A")))
        elif ord('a') <= char_code <= ord('z'):
            offset = char_code - ord("a")
            new_offset = (offset - shift) % 26
            decrypt_list.append(chr(new_offset + ord("a")))
        else:
            decrypt_list.append(char)
    decrypt_result = ''.join(decrypt_list)
    print("待解密密文:", cipher_text)
    print("解密结果:", decrypt_result)
    return decrypt_result

# 主执行逻辑
if __name__ == '__main__':
    original_text = input('输入需要加密的文本: ')
    cipher = encrypt(original_text)
    input_cipher = input('输入需要解密的文本: ')
    decrypt(input_cipher)

验证效果

输入Hello World!测试,加密结果为Khoor Zruog!,解密该密文可得到原始的Hello World!,结果完全匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 11:06:05