I got NameError when I try to run this codes.”global name j is not defined”. How can I fix it?
def test(j):
for i in range(j):
j = i**2
if __name__=='__main__':
from timeit import Timer
j = 30
t = Timer("test(j)","from __main__ import test")
print( t.timeit(j))
Timerdoesn’t know aboutj. You need to do something like"test(%d)" % j(orfrom __main__ import jor put the definition ofjinside the string, too).Also, the argument to
timeitis different from the argument to yourtestfunction (so the different uses ofjare probably not what you should do or mean). The timeit argument gives the number of executions for the test function.p.s. Note that you need to indent any code in your question to get it formatted
p.p.s. There used to be a comment here about not using
from __main__ importbut that actually does work!