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

后端 未结 5 902
不思量自难忘°
不思量自难忘° 2020-12-05 23:11

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 decla

相关标签:
5条回答
  • 2020-12-05 23:38

    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.

    0 讨论(0)
  • 2020-12-05 23:47

    From the Python Docs

    Names listed in a global statement must not be used in the same code block textually preceding that global statement.

    0 讨论(0)
  • 2020-12-05 23:52

    From the Python documentation:

    Names listed in a global statement must not be used in the same code block textually preceding that global statement.

    https://docs.python.org/reference/simple_stmts.html#global

    So moving global times to the top of the function should fix it.

    But, you should try not to use global in this situation. Consider using a class.

    0 讨论(0)
  • 2020-12-05 23:53

    For the main program, you can declare it on the top. Ther will be no warning. But, as said, the global mention is not useful here. Each variable put in the main program is in the global space. In functions, you must declare that you want use the global space for it with this keyword.

    0 讨论(0)
  • 2020-12-05 23:55

    This program should work but may not work exactly as you intended. Please take note of the changes.

    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)
    
    def main():
        while True:
            print ("Do you want to...")
            print ("1. Time your solving")
            print ("2. See your solvings")
            dothis = input(":: ")
            if dothis == "1":
                timeit()
            elif dothis == "2":
                sorted_times = sorted(times)
                sorted_times.reverse()
                for curr_time in sorted_times:
                    print("%d - %f" % ((sorted_times.index(curr_time)+1), curr_time))
                break
            else:
                print ("WTF? Please enter a valid number...")
    
    main()
    
    0 讨论(0)
提交回复
热议问题