0

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))
2
  • 1
    Why keep using the variable j in many different contexts? Commented Jul 26, 2010 at 8:31
  • from __main__ import test, j works and you have too many j s Commented Jul 26, 2010 at 8:40

1 Answer 1

3

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!

Sign up to request clarification or add additional context in comments.

1 Comment

from __main__ import test works, try it. Is it preferred? Dunno, but would welcome an explanation why not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.