簡體   English   中英

UnboundLocalError:在函數賦值之前引用了局部變量“n”

[英]UnboundLocalError: local variable 'n' referenced before assignment in function

我必須創建一個函數來找到n是整數的最小m n=(r/(Rr))*m

我不斷收到錯誤消息: local variable 'n' referenced before assignment. 我嘗試在函數的開頭使用全局n ,但隨后出現錯誤: name 'n' is not defined將不勝感激。 謝謝你。 這是我的代碼:

def courbeFerme(R,r):
    global n
    if (R in range(0,1000)) and (r in range(0,1000)):
        m=0
        while ((r/(R-r))*m).is_integer()==False: 
            m+=1
            n=(r/(R-r))*m           
        return n

如果您的while循環的條件在第一次測試中失敗,您永遠不會分配給n ,但您仍會嘗試return它。 您需要:

  1. 確保分配總是至少發生一次,或
  2. 在全局范圍內給n一個默認值,這樣即使您沒有在函數中分配給它,它也可以讀取一些內容。

如果它不是一個global ,同樣的解決方案適用,但你必須在進入函數時給它一個默認值。

暫無
暫無

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

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