Python Forum

Full Version: code for a timer
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi I am using Python 3.6.2 I used a def so it would be easier to use this timer but my code doesn't seem to work can someone help me. I also showed the error that I am getting when I type "mycounter(10)"
 def mycounter(time):
	for x in range(1, time):
		print(count)
		count = count + 1
		time.sleep(1)
		if count == time:
			count = 0
Error:
Traceback (most recent call last): File "<pyshell#74>", line 1, in <module> mycounter(10) File "<pyshell#73>", line 3, in mycounter print(count) UnboundLocalError: local variable 'count' referenced before assignment
first, you need to import "time". Never use keywords or module names as variables. You need to indent correctly (in Python, that is four spaces). Finally, you need to "call" your function.

import time
def mycounter(lapse):
    count = 0
    for x in range(1, lapse):
        print(count)
        count = count + 1
        time.sleep(1)
        if count == lapse:
            count = 0

mycounter(10)
Output:
0 1 2 3 4 5 6 7 8
just to mention that you don't need both x and count variables.
import time
def mycounter(lapse):
    for counter in range(lapse):
        time.sleep(1)
        print(counter)
 
mycounter(10)
this will count 10 seconds (0-9)