python global variable not defined in for loop

后端 未结 4 2131
日久生厌
日久生厌 2021-01-06 14:10

This code gives the error: UnboundLocalError: local variable \'LINES\' referenced before assignment but LINES is clearly initialized since if I com

相关标签:
4条回答
  • 2021-01-06 14:24

    You can access global variable from inside foo, but you can't rebind them unless the global keyword is used

    So you can use LINES.append(...) or LINES[:] = [] as they are merely modifying the list that LINES references.

    When you try to assign to LINES using LINES = [], Python knows it needs to create an entry for LINES in the functions local variables. Since you are trying to use len(LINES) before assigning anything to the local variable, it causes an error

    You can inspect foo like this

    >>> foo.func_code.co_nlocals
    2
    >>> foo.func_code.co_varnames
    ('prob', 'LINES')
    

    If you define foo again without the LINES = [], you'll see that Python no longer marks it as a local variable.

    0 讨论(0)
  • 2021-01-06 14:24

    You need to use the global keyword:

    def foo():
      global LINES
      for prob in range(1,3):
        print "len(lines) = %d" % len(LINES)
        LINES = []
    

    Otherwise, Python will think that LINES is local, and printing out the value before setting it to [] will be an issue

    You can get the value of global variable LINES by printing it out, but when you have the statement

    LINES = []
    

    which tries to set LINES to a new list, Python interprets it as a local variable

    0 讨论(0)
  • 2021-01-06 14:34

    As Desired Login said,

    Since you assign to LINES in your example function, python knows not to use the global variable, but you attempt to access this variable before you define it.

    This is not the end, you can fix this by using a global keyword, telling python that the LINES in the function is the same as the LINES outside of the function.

    Try:

    LINES = []
    
    def foo():
      global lines
      for prob in range(1,3):
        print "len(lines) = %d" % len(LINES)
        LINES = []
    
    if __name__ == "__main__":
      foo()
    
    0 讨论(0)
  • 2021-01-06 14:40

    Python will first look in the function scope for your variable, before it looks in the global (module level) scope. Since you assign to LINES in your example function, python knows not to use the global variable, but you attempt to access this variable before you define it. You should either initialise LINES before the print statement, or leave out the LINES = [] statement.

    0 讨论(0)
提交回复
热议问题