当我在函数中定义变量名称时,为什么会收到 NameError 错误? [重复]

问题描述 投票:0回答:1

当我尝试运行此代码时,在

NameError
语句处出现
if
,告诉我
net_affect
未定义。

h, m, s, t = input('Rate each of the following Emotions and hit enter:\nHappiness (1-7):'), input('Meaningfulness (1-7):'), input('Stressfulness (1-7):'), input('Tiredness (1-7):')
h_int=int(h)
m_int=int(m)
s_int=int(s)
t_int=int(t)
def na():
    add_h_m = h_int + m_int
    div_h_m = add_h_m/2
    add_s_t = s_int + t_int
    div_s_t = add_s_t/2
    net_affect = div_h_m - div_s_t
    print(net_affect)
na()

if net_affect >= 3:
    print("Doing Well")
elif net_affect <3 and net_affect >0:
    print("Doing Okay")
else:
    print("Not Good")

这是完整的终端输出:

C:\Users\mrkev\Desktop\PAI 724>python ex2.py
Rate each of the following Emotions and hit enter:
Happiness (1-7):6
Meaningfulness (1-7):7
Stressfulness (1-7):4
Tiredness (1-7):3
3.0
Traceback (most recent call last):
  File "C:\Users\mrkev\Desktop\PAI 724\ex2.py", line 16, in <module>
    if net_affect >= 3:
NameError: name 'net_affect' is not defined

为什么会出现这种情况?我认为通过在函数中定义 net_affect(并调用它),我可以将它用作程序其余部分中的变量。

python function if-statement cmd atom-editor
1个回答
2
投票

在文档或教程中查找“变量范围”。

net_affect
变量是
na
函数的局部变量。 您无法从外部访问它,并且当函数返回时它会被删除。

您也可以:

  • 在函数外部定义变量,并表明您在函数中使用它

    net_affect = None
    def na():
        ...
        global net_affect
        net_affect = div_h_m - div_s_t
    
    
  • 从函数返回值并捕获返回值

    def na():
        ...
        net_affect = div_h_m - div_s_t
        ...
        return net_affect                # return the value
    
    ...
    net_affect_new = na()                # catch the value
    

    注意:

    net_affect_new
    可以称为
    net_affect
    ,但它们不是相同的变量,它们位于两个不同的范围内。

© www.soinside.com 2019 - 2024. All rights reserved.