Reputation: 77
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))
Upvotes: 0
Views: 719
Reputation: 27087
Timer
doesn't know about j
. You need to do something like "test(%d)" % j
(or from __main__ import j
or put the definition of j
inside the string, too).
Also, the argument to timeit
is different from the argument to your test
function (so the different uses of j
are 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__ import
but that actually does work!
Upvotes: 3