将函数返回值赋值给变量时遇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
NameErrorwhen 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 thinksevaluate()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 = 2andreturn awith 4 spaces (the standard Python indentation) to tell Python these lines belong inside theevaluate()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
相关产品推荐
相关产品推荐

