簡體   English   中英

當我在函數中定義變量名時,為什么會出現 NameError?

[英]Why am I getting a NameError when I've defined my variable name in a function?

我正在嘗試根據輸入語句和我定義的函數構建 if/elif/else 語句。 當我運行代碼時,輸​​入語句和函數定義並調用運行良好,但隨后我進入了 if/elif/else 語句並得到了一個 NameError,告訴我我在 if/elif/ 中調用了一個變量else 語句未定義(即使我認為我在函數中定義了它)。

對於上下文,我是 Python 的新手,我正在 Atom 中構建代碼並在命令提示符中運行它。

我的輸入、函數定義和 if 語句代碼如下所示:

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,然后我可以在我的程序中將其用作變量。

感謝您的幫助!

在您的文檔或教程中查找“變量范圍”。

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但它們不是相同的變量,它們在兩個不同的范圍內。

或者干脆

def na():
    ...
    return div_h_m - div_s_t

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM