name 'times' is used prior to global declaration - But IT IS declared
Asked Answered
C

8

46

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.

Crusty answered 20/1, 2010 at 22:43 Comment(0)
G
49

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.

Gaullist answered 20/1, 2010 at 22:48 Comment(3)
Darn it! Now, when I choose option 2 to show me my results, this shows up: AttributeError: 'NoneType' object has no attribute 'reverse', referring to sorted_times = sorte_times.reverse()Crusty
That's because times.sort() returns None. You should use either times.sort(); print times or print sorted(times).Gaullist
For python newbies like me: I realized that the best is to declare a variable global right at the beginning of the function in which it is used (and not just right before it is written to).Inman
M
35

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.

Midway answered 20/1, 2010 at 22:49 Comment(0)
T
2

From the Python Docs

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

Trotline answered 20/1, 2010 at 22:54 Comment(0)
B
2
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 ;)

Baywood answered 27/6, 2021 at 19:8 Comment(3)
While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.Airel
I already told. Because you must write the "global<varname>" at startBaywood
this was the problemBaywood
P
0

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()
Posology answered 20/1, 2010 at 22:56 Comment(0)
A
0

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
Atalaya answered 8/1, 2023 at 16:36 Comment(0)
T
-1

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.

Talton answered 29/9, 2016 at 9:5 Comment(0)
L
-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
Legislatorial answered 3/10, 2023 at 6:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.