Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
code for a timer
#1
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
Reply
#2
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
If it ain't broke, I just haven't gotten to it yet.
OS: Windows 10, openSuse 42.3, freeBSD 11, Raspian "Stretch"
Python 3.6.5, IDE: PyCharm 2018 Community Edition
Reply
#3
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)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Running a few lines of code as soon as my timer ends nethatar 3 2,355 Feb-26-2021, 01:02 PM
Last Post: jefsummers
  email timer/rss feed timer ndiniz 1 2,045 Feb-02-2021, 07:18 PM
Last Post: nilamo
  code keeps running if i use from threading import timer? birddseedd 3 2,565 Jan-25-2019, 05:00 AM
Last Post: stullis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020