python global variable not defined in for loop

后端 未结 4 2160
日久生厌
日久生厌 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: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()
    

提交回复
热议问题