开发者

NameError for using timeit in python

I got NameError when I try to run this codes."global name j is not defined". How can I fix it?

开发者_Go百科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))


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜