[英]UnboundLocalError: local variable 'n' referenced before assignment in function
I have to create a function that will find the smallest m
for which n
is an integer.我必须创建一个函数来找到n
是整数的最小m
。 n=(r/(Rr))*m
I keep getting the error: local variable 'n' referenced before assignment.
我不断收到错误消息: local variable 'n' referenced before assignment.
I tried using global n
at the beginning of my function but then I get error : name 'n' is not defined
Help would be much appreciated.我尝试在函数的开头使用全局n
,但随后出现错误: name 'n' is not defined
将不胜感激。 Thank you.谢谢你。 Here is my code:这是我的代码:
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
If your while
loop's conditional fails on the first test, you never assign to n
, but you still try to return
it.如果您的while
循环的条件在第一次测试中失败,您永远不会分配给n
,但您仍会尝试return
它。 You need to either:您需要:
n
a default value at global scope, so it has something to read even if you don't assign to it in the function.在全局范围内给n
一个默认值,这样即使您没有在函数中分配给它,它也可以读取一些内容。 If it's not to be a global
, the same solution applies, but you have to give it a default value on entry to the function.如果它不是一个global
,同样的解决方案适用,但你必须在进入函数时给它一个默认值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.