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

凯撒密码部分字母加密异常,Python代码调试求助

凯撒密码加密乱码问题修复

问题根源

  1. 条件判断遗漏边界情况:原代码只处理了移位后ASCII码超过Z(90)或z(122)的情况,但没处理移位后低于A(65)或a(97)的场景(比如大写字母A左移2位),这部分字母会直接生成非字母符号。
  2. 用户选择逻辑错误:if user_choice == "Encrypt" or "encrypt" 是语法坑,等价于(user_choice == "Encrypt") or True,不管输入什么都会执行加密,后续加解密切换会失效。
  3. 加密逻辑冗余:没必要先计算移位字符再判断是否合规,你写的index_higher_90/index_higher_122函数本身已经通过模运算处理了所有循环情况,直接复用即可。

修正后的代码

# Caeser Encryption Method

def shift_upper(shift, original_letter):
    shift = shift % 26
    return chr((ord(original_letter) - 65 + shift) % 26 + 65)

def shift_lower(shift, original_letter):
    shift = shift % 26
    return chr((ord(original_letter) - 97 + shift) % 26 + 97)

def encrypt():
    ciphertext = ""
    plaintext = input("Enter plaintext and I'll cipher it: ")
    shift = int(input("Set the shift index: "))

    for char in plaintext:
        if char.isupper():
            ciphertext += shift_upper(shift, char)
        elif char.islower():
            ciphertext += shift_lower(shift, char)
        else:
            ciphertext += char
    print(ciphertext)

def decrypt():
    ciphertext = input("Enter ciphertext and I'll decrypt it: ")
    shift = int(input("Set the shift index: "))
    plaintext = ""
    for char in ciphertext:
        if char.isupper():
            plaintext += shift_upper(-shift, char)
        elif char.islower():
            plaintext += shift_lower(-shift, char)
        else:
            plaintext += char
    print(plaintext)

if __name__ == '__main__':
    user_choice = input("Encrypt or Decrypt ")
    if user_choice in ("Encrypt", "encrypt"):
        encrypt()
    elif user_choice in ("Decrypt", "decrypt"):
        decrypt()
    else:
        print("Invalid choice, please enter Encrypt or Decrypt")

关键修改说明

  • 去掉原加密函数里冗余的越界判断,直接对每个字母按大小写调用移位函数,模运算会自动处理所有循环情况(不管左移还是右移)。
  • 修正主函数的选择判断逻辑,用in操作符匹配有效输入,避免语法错误。
  • 补充了解密函数示例,解密只需传入负的移位值,复用加密的移位逻辑即可。

内容的提问来源于stack exchange,提问作者The one above all

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 15:53:11