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

Python简易字符串加密代码运行报NameError错误求排查

错误分析

  • 核心报错原因是main函数中调用prep_plaintext时传入的plaintext变量未提前定义,程序无法识别该变量触发NameError。
  • 额外存在两处语法问题:prep_plaintext函数内的print语句字符串非法换行、encrypt函数列表推导式括号配对错误,运行时也会触发报错。

修复后完整代码

def main():
    # 可自行修改下方明文内容
    plaintext = "请输入你要加密的明文"
    message = prep_plaintext(plaintext)
    rails = build_rails(message)
    encrypt(rails)

def prep_plaintext(plaintext):
    message = "".join(plaintext.split())
    message = message.upper()
    print("plaintext = {}".format(plaintext))
    return message

def build_rails(message):
    evens = message[::2]
    odds = message[1::2]
    rails = evens + odds
    return rails

def encrypt(rails):
    ciphertext = ' '.join([rails[i:i+5] for i in range(0, len(rails), 5)])
    print("ciphertext = {}".format(ciphertext))

if __name__ == '__main__':
    main()

修改说明

  • 在main函数起始位置新增plaintext变量定义,赋值为你需要加密的字符串即可
  • 删除prep_plaintext中print语句字符串内的多余换行,修正语法错误
  • 修正encrypt函数列表推导式末尾的括号配对问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 20:15:03