Welcome to OStack Knowledge Sharing 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 answer this question.

Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...