名称“时代”在全局声明之前使用 - 但它已声明

发布于 2024-08-18 05:22:25 字数 1101 浏览 13 评论 0原文

我正在编写一个小程序,用于计时并以有序的方式显示我的魔方解决方案。但是 Python (3) 一直困扰着我在全局声明之前使用的时间。但奇怪的是,它在一开始就被声明为 times = [] (是的,它是一个列表),然后又在函数上(这就是他抱怨的地方)声明为 times = [some, odd, 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()

任何帮助将非常感激,因为我是 Python 世界的新手。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

风筝在阴天搁浅。 2024-08-25 05:22:25

全局声明是当你声明timesglobal时,

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

如果一个变量被声明为global,那么在声明之前就不能使用它。

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

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.

独留℉清风醉 2024-08-25 05:22:25

来自 Python 文档:

全局语句中列出的名称不得在同一代码块中使用
文本位于该全局声明之前。

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

因此,将global times移动到函数顶部应该可以解决这个问题。

但是,在这种情况下您应该尽量不要使用global。考虑使用一个类。

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.

浪推晚风 2024-08-25 05:22:25

来自 Python 文档

全局语句中列出的名称不得在该全局语句之前的同一代码块中使用。

From the Python Docs

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

回忆躺在深渊里 2024-08-25 05:22:25
import time

times = []

def timeit():
    global times
    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)
    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()

那应该有效。 “global[varname]”必须从定义开始;)

import time

times = []

def timeit():
    global times
    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)
    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()

that should work. The "global[varname]" have to be at start from definition ;)

囚我心虐我身 2024-08-25 05:22:25

该程序应该可以运行,但可能无法完全按照您的预期运行。请注意这些变化。

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

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()
深海夜未眠 2024-08-25 05:22:25

我得到了同样的错误如下:

语法错误:名称“x”在全局声明之前使用

当尝试在inner()中使用本地和全局变量x时,如下所示:

x = 0
def outer():
    x = 5
    def inner():        
        x = 10 # Local variable
        x += 1
        print(x)
        
        global x # Global variable
        x += 1
        print(x)
    inner()
outer()

并且,当尝试使用inner()中的非局部变量和全局变量x如下所示:

x = 0
def outer():
    x = 5
    def inner():
        nonlocal x # Non-local variable
        x += 1
        print(x)
        
        global x # Global variable
        x += 1
        print(x)
    inner()
outer()

所以,我将x重命名为y 对于局部变量,如下所示:

x = 0
def outer():
    x = 5
    def inner():        
        y = 10 # Here
        y += 1 # Here
        print(y) # Here
        
        global x        
        x += 1
        print(x)
    inner()
outer()

然后,错误得到解决,如下所示:

11
1

并且,我将非局部变量的x重命名为y,如下所示:

x = 0
def outer():
    y = 5 # Here
    def inner():
        nonlocal y # Here
        y += 1 # Here
        print(y) # Here
        
        global x
        x += 1
        print(x)
    inner()
outer()

然后,错误就解决了,如下图:

6
1

I got the same error below:

SyntaxError: name 'x' is used prior to global declaration

When trying to use the local and global variables x in inner() as shown below:

x = 0
def outer():
    x = 5
    def inner():        
        x = 10 # Local variable
        x += 1
        print(x)
        
        global x # Global variable
        x += 1
        print(x)
    inner()
outer()

And, when trying to use the non-local and global variables x in inner() as shown below:

x = 0
def outer():
    x = 5
    def inner():
        nonlocal x # Non-local variable
        x += 1
        print(x)
        
        global x # Global variable
        x += 1
        print(x)
    inner()
outer()

So, I renamed x to y for the local variable as shown below:

x = 0
def outer():
    x = 5
    def inner():        
        y = 10 # Here
        y += 1 # Here
        print(y) # Here
        
        global x        
        x += 1
        print(x)
    inner()
outer()

Then, the error was solved as shown below:

11
1

And, I renamedx to y for the non-local variable as shown below:

x = 0
def outer():
    y = 5 # Here
    def inner():
        nonlocal y # Here
        y += 1 # Here
        print(y) # Here
        
        global x
        x += 1
        print(x)
    inner()
outer()

Then, the error was solved as shown below:

6
1
芯好空 2024-08-25 05:22:25

对于主程序,可以在顶部声明。不会有任何警告。但是,如前所述,全局提及在这里没有用。主程序中放置的每个变量都位于全局空间中。在函数中,您必须使用 this 关键字声明您想要使用全局空间。

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.

一杯敬自由 2024-08-25 05:22:25

我只是记录一些读书笔记,如有错误,欢迎指正。

感谢@Super Kai - Kazuya Ito 提供的示例。这让我想起了在Python中

全局变量是在任何函数外部或全局范围内声明的变量。

因此,如果要定义一个全局变量,则无需在函数外部使用 global x 进行声明,只需执行 x=1 # Global variable 即可。

需要在函数内部使用 global x 才能调用函数外部定义的全局变量,或者更改全局变量。否则,变量 x 在函数内部仍然未定义,除非您按如下方式命名另一个内部变量“x=4”:

x = 1
def outer():
    x = 5   # local variable for outer()
    def inner():        
        y = 10 # Local variable
        y += 1
        print(y)
        
        x = 4   #local variable for inner()
        x += 1
        print(x)
    inner()
outer()
print(x)

这给出了输出

11
5
1

I am just recording some reading notes and it is more than welcome if any of the following is wrong.

Thanks for the examples by @Super Kai - Kazuya Ito. It reminds me that in python

Global variables are variables declared outside of any function or in the global scope.

Thus if one wants to define a global variable, there is no need to use global x to declare outside of function, just do x=1 # Global variable.

One needs to use global x inside of a function in order to call the global variable defined outside of the function, or to change the global variable. Otherwise the variable x is still undefined inside the function, unless you name another inside variable `x=4' as follows:

x = 1
def outer():
    x = 5   # local variable for outer()
    def inner():        
        y = 10 # Local variable
        y += 1
        print(y)
        
        x = 4   #local variable for inner()
        x += 1
        print(x)
    inner()
outer()
print(x)

which gives the output

11
5
1
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文