简体   繁体   English

UnboundLocalError:在函数赋值之前引用了局部变量“n”

[英]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:您需要:

  1. Ensure that assignment always occurs at least once, or确保分配总是至少发生一次,或
  2. Give 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.

相关问题 UnboundLocalError:赋值前引用了局部变量“n” - UnboundLocalError: local variable 'n' referenced before assignment UnboundLocalError:局部变量<function>赋值前引用</function> - UnboundLocalError: local variable <function> referenced before assignment UnboundLocalError:仅在导入的函数中赋值之前引用的局部变量 - UnboundLocalError: local variable referenced before assignment in imported function only Zip() 函数返回 UnboundLocalError:赋值前引用了局部变量“zip” - Zip() function returning UnboundLocalError: local variable 'zip' referenced before assignment UnboundLocalError:赋值之前(在函数的返回部分中)引用的本地变量“用户名” - UnboundLocalError: local variable 'username' referenced before assignment (in a return part of a function) 递归总和 function(“UnboundLocalError:赋值前引用的局部变量”) - Recursive sum function (“ UnboundLocalError: local variable referenced before assignment”) 调用 function 时出现“UnboundLocalError:赋值前引用的局部变量” - "UnboundLocalError: local variable referenced before assignment" when calling a function UnboundLocalError:分配前已引用局部变量“ truebomb” - UnboundLocalError: local variable 'truebomb' referenced before assignment UnboundLocalError:分配前已引用局部变量“ cur” - UnboundLocalError: local variable 'cur' referenced before assignment UnboundLocalError:分配前已引用局部变量“ Counter” - UnboundLocalError: local variable 'Counter' referenced before assignment
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM