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

将函数返回值赋值给变量时遇NameError,PyCharm报Unresolved Reference如何解决?

Fixing NameError and "Unresolved Reference" in Your Python Code

Hey there, let's walk through fixing the issues you're facing with your code. The root problem here is incorrect indentation—Python relies heavily on indentation to define code blocks, and your current code isn't following that rule.

Let's look at your original code:

def evaluate(): a=2 return a print(evaluate())

This code is all on one line without proper indentation, so Python doesn't recognize that a=2 and return a are part of the evaluate() function. That's why:

  • You get a NameError when running it—your function isn't properly defined to return a value.
  • PyCharm marks evaluate() with a red underline: the IDE can't parse the broken function definition, so it thinks evaluate() isn't a valid reference.

Here's the corrected code with proper indentation:

def evaluate():
    a = 2
    return a

print(evaluate())

What changed and why it works:

  • We indented a = 2 and return a with 4 spaces (the standard Python indentation) to tell Python these lines belong inside the evaluate() function.
  • We moved print(evaluate()) outside the function (no indentation) so it runs as top-level code after the function is defined.

When you run this corrected code, evaluate() will properly return the value 2, and print() will output that value. PyCharm will also stop showing the "unresolved reference" error, since it can now correctly recognize the fully defined evaluate() function.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 04:06:22