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

使用codecs模块定义Rot13编解码函数时遭遇NameError问题

解决Rot13编解码函数中的NameError和结果不生效问题

问题分析

你的代码遇到两个核心问题:

  1. NameError报错:这个错误大概率是因为你在Python 2环境下运行代码导致的。Python 2的input()函数会把用户输入的内容当作Python表达式解析,当你输入HELLO时,它会试图寻找名为HELLO的变量,找不到就抛出NameError。而Python 3的input()是直接读取字符串,不会有这个问题。
  2. 编解码结果未输出:codecs.encode()函数不会修改原字符串(Python中字符串是不可变类型),你调用它之后没有保存返回的结果,所以打印的还是原始输入的文本,相当于白做了编解码操作。

修正后的代码

如果使用Python 3

import codecs

def rot13_encoder():
    rot13_text = input("Type the text to be encoded: ")
    # 保存编解码后的结果
    encoded_text = codecs.encode(rot13_text, 'rot_13')
    print(encoded_text)

# 调用函数
rot13_encoder()

如果使用Python 2

需要把input()替换为raw_input(),它会直接返回用户输入的字符串:

import codecs

def rot13_encoder():
    rot13_text = raw_input("Type the text to be encoded: ")
    encoded_text = codecs.encode(rot13_text, 'rot_13')
    print(encoded_text)

rot13_encoder()

验证效果

运行修正后的代码,输入HELLO会输出URYYB,输入URYYB则会还原为HELLO,完美实现Rot13的编解码(因为Rot13是对称的,编码和解码是同一个操作)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:35:32