[英]Why am I getting an UnboundLocalError while trying to assign a variable?
I want to assign a local variable, "length" in "main()", to the value returned by another funcion. 我想将本地函数“ main()”中的“ length”分配给另一个函数返回的值。 Yet, while I am assigning the variable, IDLE tells me that I am referencing it before assigning it.
但是,在分配变量的同时,IDLE告诉我在分配变量之前先对其进行引用。 How do I assign this local variable such that it doesn't cause an error?
如何分配此局部变量,使其不会引起错误?
import random
def length():
return 2
def main():
length = length()
index = random.randrange(0, length)
main()
I expected to assign "length" to "2" by referencing length(). 我希望通过引用length()将“ length”分配为“ 2”。 It seems to me that "length = length()" is a straightforward, correct assignment.
在我看来,“ length = length()”是一个简单,正确的赋值。
The IDLE traceback is: 空闲回溯是:
Traceback (most recent call last):
File "/home/user/code/test1.py", line 10, in <module>
main()
File "/home/user/code/test1.py", line 7, in main
length = length()
UnboundLocalError: local variable 'length' referenced before assignment
length
is either a local variable containing an integer, or global variable referring to the function. length
是包含整数的局部变量,或者是引用该函数的全局变量。 It can't be both. 不能两者兼有。 As soon as you assign to it, it's a local variable throughout the function, and therefore there is no reference to the length function any more.
分配给它后,它便是整个函数的局部变量,因此不再引用长度函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.