1

I want to make a timer, so that at the end of the timer, the timer changes the value of 'timerdone'. At the end of my timer, it doesn't change the value.

Example Code:

from time import sleep

timerdone = False

def timer():
    print "3"
    sleep(1)
    print "2"
    sleep(1)
    print "1"
    sleep(1)
    timerdone = True

timer()

if timerdone == True:
    print "BOOM!"
else:
    print "Something wrong."

When I run this in terminal, it prints "Something wrong." instead of "BOOM". I know that I can just make it print "BOOM!" at the end of the timer, but this is just a simpler way of showing my problem.

3 Answers 3

1

You're not returning timerdone, so all you're doing is creating a new variable name timedone in the function and setting it to false. You should return it instead.

from time import sleep

def timer():
    print "3"
    sleep(1)
    print "2"
    sleep(1)
    print "1"
    sleep(1)
    return True   


if timer():
    print "BOOM!"
else:
    print "Something wrong."
Sign up to request clarification or add additional context in comments.

Comments

1

You need to return the value. So:

from time import sleep

timerdone = False

def timer():
    print "3"
    sleep(1)
    print "2"
    sleep(1)
    print "1"
    sleep(1)
    return True

timerdone = timer()

if timerdone == True:
    print "BOOM!"
else:
    print "Something wrong."

Global variables will also work but returning a value is usually a better practice.

Comments

0

You need to make your variable global.

def timer():
    global timerdone
    print "3"
    sleep(1)
    print "2"
    sleep(1)
    print "1"
    sleep(1)
    timerdone = True

If you do not use the keyword global, the variable timerdone refers to the local scope of the function timer().

Note that you can access and so read global variable without specifying the keyword, but global is needed if you want to change its value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.