Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (120 points)

why does python timeit give this error: NameError: name 'w1' is not defined

I have an assignment where i have to create a couple of functions and then use the timeit module to see which one is faster. The functions work very well on their own but when i use the timeit module it keeps giving me the NameError. I know there are a lot of ways to time your function but i am supposed to use "timeit". I am also supposed to use timeit inside the main function and time this at least a 100 times(which is why i made that for loop)

This is what my code looks like:

from timeit import timeit

def function1(w1):

    lowercase = ""

    for x in w1:

        if x.isalpha():

            lowercase += x.lower()

    return lowercase

if __name__ is "__main__":

    w1 = "houseE134"

    for x in range(1, 100):

        print(x)

        print(timeit("function1(%s)" % w1 , "from __main__ import function1", number=100))

unfortunately i keep getting this error no matter what i try:

NameError: name 'w1' is not defined

Does anyone know how to fix this?
Welcome To Ask or Share your Answers For Others

Please log in or register to reply this article.

OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...