tags:

views:

47

answers:

1

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))
+3  A: 

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!

Andrew Jaffe
`from __main__ import test` works, try it. Is it preferred? Dunno, but would welcome an explanation why not.
msw
yes it is working with that too!
masti
correct -- I didn't realize that idiom worked. Fixed.
Andrew Jaffe