名称'times'在全球申报之前使用 - 但是它被宣布了!

Ant*_*oPT 30 python global-variables python-3.x

我正在为一个小程序编写时间,并以有序的方式展示我的魔方解决方案.但Python(3)一直困扰着我在全球宣言之前使用的时间.但奇怪的是,IT正在开始时被宣布为times = [](是的,它是一个列表),然后再次,在函数(这是他抱怨的地方)times = [some, weird, list]和"全局化"它global times.这是我的代码,因此您可以根据需要进行分析:

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()
Run Code Online (Sandbox Code Playgroud)

任何帮助都会非常感激,因为我是Python世界的新人:)

Joh*_*kin 34

全局声明是当你声明timesglobal

def timeit():
    global times # <- global declaration
    # ...
Run Code Online (Sandbox Code Playgroud)

如果声明了变量global,则在声明之前不能使用它.

在这种情况下,我认为你根本不需要声明,因为你没有分配times,只是修改它.


car*_*arl 21

从Python文档:

Names listed in a global statement must not be used in the same code block
textually preceding that global statement.
Run Code Online (Sandbox Code Playgroud)

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

所以,移动global times到函数的顶部应该没问题.

但是,在这种情况下,你应该尽量不使用全局变量.考虑使用一个类.