This works fine:
import time
def load():
a = 0
l = range(10000000)
b = 100/len(l)
start = time.time()
for i in l:
a += b
end = time.time()
print(end-start)
load()
Now I want my function to use a
as a global variable:
import time
a = 0
def f():
global a
a = 0
def load():
l = range(10000000)
b = 100/len(l)
start = time.time()
for i in l:
a += b
end = time.time()
print(end-start)
f()
load()
But it returns an Error: UnboundLocalError: local variable 'a' referenced before assignment
Edit:
I found this in a thread and it works:
globvar = 0
def set_globvar_to_one():
global globvar # Needed to modify global copy of globvar
def print_globvar():
print(globvar) # No need for global declaration to read value of globvar
set_globvar_to_one()
print_globvar() # Prints 1
But what is the difference to my function?