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
847 views
in Technique[技术] by (71.8m points)

python - name 'times' is used prior to global declaration - But IT IS declared!

I'm coding a small program to time and show, in a ordered fashion, my Rubik's cube solvings. But Python (3) keeps bothering me about times being used prior to global declaration. But what's strange is that IT IS declared, right on the beggining, as times = [] (yes, it's a list) and then again, on the function (that's where he complains) as times = [some, weird, list] and "globaling" it with global times. Here is my code, so you may analyse it as you want:

import time

times = []

def timeit():
    input("Press ENTER to start: ")
    start_time = time.time()
    input("Press ENTER to stop: ")
    end_time = time.time()
    the_time = round(end_time - start_time, 2)
    print(str(the_time))
    times.append(the_time)
    global times
    main()

def main():
    print ("Do you want to...")
    print ("1. Time your solving")
    print ("2. See your solvings")
    dothis = input(":: ")
    if dothis == "1":
        timeit()
    elif dothis == "2":
        sorte_times = times.sort()
        sorted_times = sorte_times.reverse()
        for curr_time in sorted_times:
            print("%d - %f" % ((sorted_times.index(curr_time)+1), curr_time))
    else:
        print ("WTF? Please enter a valid number...")
        main()

main()

Any help would be very appreciated as I'm new in the world of Python :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The global declaration is when you declare that times is global

def timeit():
    global times # <- global declaration
    # ...

If a variable is declared global, it can't be used before the declaration.

In this case, I don't think you need the declaration at all, because you're not assigning to times, just modifying it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...