简体   繁体   中英

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. Yet, while I am assigning the variable, IDLE tells me that I am referencing it before assigning it. 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(). It seems to me that "length = length()" is a straightforward, correct assignment.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM