名称'times'在全球声明之前使用 - 但IT被宣布! [英] name 'times' is used prior to global declaration - But IT IS declared!

查看:878
本文介绍了名称'times'在全球声明之前使用 - 但IT被宣布!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个小程序,以有序的方式计时和展示我的魔方解决问题。但是Python(3)在全局声明之前一直使用的时候一直困扰着我。但奇怪的是,它在开始时被声明为 times = [] (是的,它是一个列表),然后再次在函数中声明抱怨)为 times = [some,weird,list] ,并用 global times 将其全局化。这里是我的代码,所以你可以分析它,只要你想:

 进口时间

次数= []

def timeit():
input(按ENTER开始:)
start_time = time.time()
input(按ENTER停止:)
end_time = time.time()
the_time = round(end_time - start_time,2)
print(str(the_time))
times.append(the_time)
全球时间
main()

def main():
print(您想要...)
print(1 (b)如果dothis ==1:
timeit ()
elif dothis ==2:
sorte_times = times.sort()
sorted_times = sorte_times.reverse()
for sorted_times中的curr_time:
print (%d - %f%((sorted_times.index(curr_time)+1),curr_time))
else:
print(WTF?请输入一个有效的数字...)
main()

main()

任何帮助都将非常值得赞赏,因为我是新手)

解决方案

全局声明是当你声明 times global

  def timeit():
全局时间#< - 全局声明
#...

如果声明了一个变量 global ,它不能在声明前使用。在这种情况下,我不认为你完全需要声明,因为你不是分配给 times ,只是修改它。


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 :)

解决方案

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.

这篇关于名称'times'在全球声明之前使用 - 但IT被宣布!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆