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

Python运行报NameError:correct_answer未定义 报错求解

NameError: name 'correct_answer' is not defined 报错修复

问题根因

代码里有3个核心问题导致报错:

  • riddle = print(random.choice(riddler))写法错误:print()是输出函数,没有有效返回值,执行后riddle变量实际被赋值为None,根本不是随机选中的谜语文本
  • 所有条件判断逻辑无效:if/elif分支里拿riddle和[riddler[x]](单元素列表)做相等判断,两边数据类型完全不匹配,所有分支永远不会执行,correct_answer变量自始至终没有被赋值,最后执行打印时自然抛出未定义错误
  • 列表内字符串格式错误:谜语列表里的文本存在无意义断行、最后一条谜语开头多余空格的问题,后续做文本匹配时容易出现匹配失败的情况

修复后可运行代码

import time 
import random

print("Here is a practice riddle for you:")
riddler = [
    "What is nowhere but everywhere, except where something is?",
    "What is green and then red?",
    "What is strong enough to smash ships but still fears the sun?",
    "The more you cut me the bigger I grow. What am I?",
    "A diamond plate, a glowing grate, a place you never leave. Where am I?"
]
answers = ["Nothing", "Frog in a blender", "Ice", "A hole", "Home"]

# 先获取随机谜语内容,再单独执行打印
riddle = random.choice(riddler)
print(riddle)

# 直接通过索引匹配对应答案,省略冗余的多分支判断
riddle_pos = riddler.index(riddle)
correct_answer = answers[riddle_pos]

print(correct_answer)

关键修改说明

  • 拆分随机选值和打印逻辑:先把random.choice(riddler)选中的谜语字符串存入riddle变量,再单独调用print输出,避免变量被赋值为None
  • 修正判断逻辑的类型错误:去掉条件判断里多余的列表包裹,保证比较的两边数据类型一致;进一步优化为用列表索引直接匹配答案,删掉冗余的5个if/elif分支
  • 修正列表内的字符串格式:把断行的字符串拼接为完整文本,删掉最后一条谜语开头的多余空格,避免隐式的匹配错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 23:33:34