pythonfunctioncountdowntimertkinter-button

Python, calling functions whitin functions; it does not give back the right value


I'm making a game where players guess a random number. If they answer fast, they get points.

The game starts with entering names. A click on the button checks if names are filled in, pops a messagebox and then calls the function 'Timer': in which 10 seconds will countdown. A player can make a guess and click on the button to see if they are close. The new function checks the time left and allocates point corresponding to your fastness.

Here is the code that doesn't work properly:

#variable to set time on 10 seconds:
Time = 10

#Function to countdown:
def Timer(Time):
    while Time:
        time.sleep(1)
        Time -= 1
        return Time

#Function when guess is made:
def Guess():
    global Time
    TimeLeft = Timer(Time)
    Time = 10
    Timer(Time)

As I said, in another function Timer() is called at the end. However; when I printed Time, I got 10 at the start of the Guess-function and after TimeLeft = Timer(Time) print said 9. As I waited a long time after the end of the function to have another guess, I expected that the value of Time would not be 10. More like 1 or 0... I hope someone can make me understand why the timer doesn't work properly :)


Solution

  • The global declaration inside a function says that within that function, assignments to the named variable will affect the global name, rather than shadowing it with a locally scoped variable.

    You use global within your Guess function, so when you assign to Time within that function, it modifies the global Time.

    In your Timer function, Time is the argument name, so it's a local variable, by definition. Assignments to Time within that function do not affect the global variable.

    If you want to rebind the global Time after calling Timer in your Guess function, you can do that by assigning the return value from Timer (which is the value of the Timer's local Time variable):

        Time = Timer(Time)
    

    Obligatory advice that's unrelated to your immediate problem: global variables usually make your code hard to debug (this is a case in point!) and it's almost always better to avoid them completely. The global in this code is actually a complete no-op because only one function accesses that variable anyway; it might as well just be a local variable.