Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Error: local variable referenced before assignment

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?

like image 767
hh54188 Avatar asked Jun 03 '26 23:06

hh54188


1 Answers

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

like image 143
Prahalad Deshpande Avatar answered Jun 06 '26 13:06

Prahalad Deshpande



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!