简体   繁体   English

为什么在尝试分配变量时出现UnboundLocalError?

[英]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.

相关问题 为什么我收到unboundLocalError? - Why am I getting an unboundLocalError? 为什么我在这段代码中收到“UnboundLocalError”? - Why am I getting “UnboundLocalError” in this code? 为什么我在 function 下面出现 unboundLocalError? - Why I am getting unboundLocalError in below function? 为什么即使我只是在定义一个变量,也会收到 UnboundLocalError? - Why am I getting an UnboundLocalError even though I am just defining a variable? 为什么在添加while循环以及if语句之后添加UnboundLocalError? - why am i getting an UnboundLocalError after i add my while loop and if then else if statements? 为什么在Python中赋值之前会收到UnboundLocalError消息,该消息指出局部变量“参与者”被引用? - Why am I getting the UnboundLocalError that says local variable 'participants' referenced before assignment in Python? 为什么我收到错误:UnboundLocalError: local variable 'lcm' referenced before assignment - Why am I getting the error: UnboundLocalError: local variable 'lcm' referenced before assignment 无法弄清楚为什么我收到UnboundLocalError - Cannot figure out why I am getting UnboundLocalError 为什么在我的Python脚本的except子句中出现UnboundLocalError? - Why am I getting an UnboundLocalError in the except clause of my Python script? 为什么在为我的石头剪刀布代码分配之前引用了 UnboundLocalError:局部变量“last_move”? - Why am I getting an UnboundLocalError: local variable 'last_move' referenced before assignment for my rock paper scissors code?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM