2

Here is my code:

import time

GLO = time.time()

def Test():
    print GLO
    temp = time.time();
    print temp
    GLO = temp

Test()

Traceback (most recent call last): File "test.py", line 11, in Test() File "test.py", line 6, in Test print GLO UnboundLocalError: local variable 'GLO' referenced before assignment

the error occurred when I add the GLO = temp, if I comment it, the function could be execute successfully, why?

How can I set GLO = temp?

hh54188
  • 14,887
  • 32
  • 113
  • 184

2 Answers2

5

Within the Test method specify that you want to refer to the globally declared GLO variable as shown below

def Test():
    global GLO #tell python that you are refering to the global variable GLO declared earlier.
    print GLO
    temp = time.time();
    print temp
    GLO = temp

A similar question can be found here : Using a global variable within a method

Community
  • 1
  • 1
Prahalad Deshpande
  • 4,709
  • 1
  • 20
  • 22
4

Python looks the whole function scope first. So your GLO refers to the one below, not the global one. And refer the LEGB rule.

GLO = time.time()

def Test(glo):
    print glo
    temp = time.time();
    print temp
    return temp

GLO = Test(GLO)

or

GLO = time.time()

def Test():
    global GLO
    print GLO
    temp = time.time();
    print temp
    GLO =  temp

Test()
Community
  • 1
  • 1
zhangyangyu
  • 8,520
  • 2
  • 33
  • 43