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

Python凯撒密码函数报错'unexpected indent',求排查缩进问题

凯撒密码代码的问题修复

你的代码存在缩进、语法和逻辑多方面错误,直接导致了"unexpected indent"报错,具体问题及修复方案如下:

主要问题点

  • 缩进层级混乱:print语句和else块的缩进未遵循Python代码块的缩进规则,同一层级的语句缩进必须完全一致
  • 语法冗余错误:else块内多余了text_direction == "decode":这行无效判断,else本身就对应if的反向分支,无需重复写条件
  • 逻辑错误:
    • 解密操作应使用position - shift_amount而非加法
    • 字符串拼接不能用-=,需统一使用+=
  • 拼写错误:deoded应为decoded,函数名ceasar建议修正为标准拼写caesar

修复后的完整代码

alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
text = input("Type your message:\n").lower()
shift = int(input("Type the shift number:\n"))

def caesar(plain_text, shift_amount, text_direction):
    cipher_text = ""
    for plain1 in plain_text: 
        position = alphabet.index(plain1)
        if text_direction == "encode":
            new_position = position + shift_amount
            new_letter = alphabet[new_position]
            cipher_text += new_letter
        else:
            new_position = position - shift_amount
            new_letter = alphabet[new_position]
            cipher_text += new_letter
    # 打印语句放在循环外,避免逐字符打印
    if text_direction == "encode":
        print(f"The encoded text is {cipher_text}")
    else:
        print(f"The decoded text is {cipher_text}")

caesar(plain_text=text, shift_amount=shift, text_direction = direction)

额外提示

Python对缩进要求严格,建议统一使用4个空格作为缩进单位,不要混用空格和制表符;由于alphabet列表重复了26个字母,解密时即使出现负数索引,Python也会自动从列表末尾往前取值,无需额外处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 11:48:22