[英]UnboundLocalError: local variable 'n' referenced before assignment
[英]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
它。 您需要:
n
一個默認值,這樣即使您沒有在函數中分配給它,它也可以讀取一些內容。 如果它不是一個global
,同樣的解決方案適用,但你必須在進入函數時給它一個默認值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.