How to create a timer that resets for quiz games? - python

I trying to create a timer for my quiz game. It should reset after every right question. But problem with my code is that it keeps increasing speed after every time it resets.
timeCount = 30
def countdown():
global timeCount
while timeCount > 0:
print(timeCount)
sleep(1)
timeCount -= 1
else:
print("Time Out!")

I think this is what you are trying to do:
import time
timeCount = 30
start = time.time()
seconds = 0
def countdown():
global timeCount
global seconds
while seconds < timeCount:
now = time.time()
seconds = now - start
print(timeCount - seconds)
else:
print("Time Out!")
countdown()
This teaches you how to use time.time. You can take away seconds from timeCount to make a timer that goes down from 30 to 0. When the seconds hits 30, you can end the loop and print "Time out". You can truncate the unnecessary floating point values, since i am assuming floating point numbers doesn't look good on a quiz timer and is unnecessary as well.
seconds = int(seconds)

You can use the function time.perf_counter() :
import time
start=time.perf_counter()
time.sleep(1) #you can replace the sleep function with the action you want to monitor
end=time.perf_counter()
print('elapsed time : ',end-start)
In the example above, time.perf_counter() evaluated the time when it is called so it gives you the elapsed time between the two call.
if you want to use your current logic :
Your 'global' statement means that your are going to modify the 'timeCount' variable during the execution of your code. To fix it, you can use a new local variable in your function (called 'local_count' in the below solution), like this you reset the countdown each time you call your function :
import time
timeCount = 30
def countdown():
local_count = timeCount
while local_count > 0:
print(local_count)
time.sleep(1)
local_count -= 1
print("Time Out!")

Related

How do I receive the updated time every time it is called in this function?

import time
seconds = time.time()
local_time = time.ctime(seconds)
print("Start Time:", local_time)
def bot():
x = 0
while x < 16:
time.sleep(1)
print("Time:", local_time)
x += 1
When I run this code it prints the initial time take before the function every time, I would like it to show the updated time every time local time is printed, can someone point me in the right direction?
Using a variable will not re-evaluate it. You'll need to calculate the time again each loop iteration
import time
def bot():
for x in range(16):
time.sleep(1)
seconds = time.time()
local_time = time.ctime(seconds)
print("Time:", local_time)
bot()

should i use for loop or while loop to make a break timer in python?

I have this code to stop a function at a specific time. I would loop through the function and then break the function, if it takes too long, is there a better way to do it?
import time
def function_one()
rec = (time.time())
print("im starting")
ans = str(time.time() - rec)
ans = (round(float(ans), 15))
print("this is where im doing something code")
while ans < 10:
return function_one()
break
You can make it simpler like this:
import time
def function_one():
start_time = time.time()
while True:
print('Function doing something ...')
if time.time() - start_time > 10:
break
function_one()
Here, I'm using a while loop just to keep the function running, but that depends on the details of your function.
In general, what you need is:
set the start time
do whatever the function is supposed to be doing;
check if it's been running for too long and, in case it has, you can simply return.
So, something like:
import time
def function_one():
start_time = time.time()
# do your job
if time.time() - start_time > 10:
return something
function_one()
If you want to stop a function after a set amount of time has passed I would use a while loop and do something like this.
import time
def function_one():
start = (time.time()) #start time
limit = 1 #time limit
print("im starting")
while (time.time() - start) < limit:
#input code to do here
pass
print(f"finished after {time.time() - start} seconds")
function_one()

How do i do some stuff and count time in parallel in python?

I want my code to take some integers for some time (e.g. 10 seconds) and to count and print time every second. So it prints time permanently and i enter some numbers whenever i want. Maybe i should use async functions?
def accepting_bets():
global list_of_bets
list_of_bets = []
list_of_bets.append(int(input()))
def main():
i = 10
while True:
print(f"{i} seconds remaining...")
time.sleep(1)
i -= 1
accepting_bets()
if i == 0:
break
print(list_of_bets)
You can move the timing code to a different thread.
I would recommend researching about multi-threading in Python if you aren't aware about it.
import threading
import time
def countTime():
i = 10
while True:
print(f"{i} seconds remaining...")
time.sleep(1)
i -= 1
if i == 0:
break
print(list_of_bets)
thread1 = threading.Thread(target=countTime)
thread1.start()
# while you want to get the input
global list_of_bets
list_of_bets = []
list_of_bets.append(int(input()))
The countTime function will keep on running on another thread, and will not be paused by the input statement

Python: Run code every n seconds and restart timer on condition

This may be simpler than I think but I'd like to create timer that, upon reaching a limit (say 15 mins), some code is executed.
Meanwhile every second, I'd like to test for a condition. If the condition is met, then the timer is reset and the process begins again, otherwise the countdown continues.
If the condition is met after the countdown has reached the end, some code is executed and the timer starts counting down again.
Does this involve threading or can it be achieved with a simple time.sleep() function?
You could probably accomplish it with threading really elegantly but if you need a quick fix you could try
import time
timer = 15 * 60 # 60 seconds times 15 mins
while timer > 0:
time.sleep(0.985) # don't sleep for a full second or else you'll be off
timer -= 1
if someCondition:
timer = 15 * 60
executeCode() # called when time is zero and while loop is exited
If the whole process is as simple as you say, I would go about it like this (semi-psuedo-code):
def run_every_fifteen_minutes():
pass
def should_reset_timer():
pass
def main():
timer = 0
while True:
time.sleep(1)
timer+=1
if should_reset_timer():
timer = 0
if timer == 15*60:
run_every_fifteen_minutes()
timer = 0
Note that this won't be exactly fifteen minutes in. It might be late by a few seconds. The sleep isn't guaranteed to sleep only 1 second and the rest of the loop will take some time, too. You could add a system time compare in there if you need it to be really accurate.
Thanks for the help everyone, your answers pointed me in the right direction. In the end I came up with:
#!/usr/bin/python
import RPi.GPIO as GPIO
import time
import subprocess
GPIO.setmode(GPIO.BCM)
PIR_PIN = 4
GPIO.setup(PIR_PIN, GPIO.IN)
timer = 15 * 60 # 60 seconds times 15 mins
subprocess.call("sudo /opt/vc/bin/tvservice -o", shell=True)
try :
print "Screen Timer (CTRL+C to exit)"
time.sleep(5)
print "Ready..."
while True:
time.sleep(0.985)
# Test PIR_PIN condition
current_state = GPIO.input(PIR_PIN)
if timer > 0:
timer -= 1
if current_state: #is true
# Reset timer
timer = 15 * 60
else:
if current_state: #is true
subprocess.call("sudo /opt/vc/bin/tvservice -p", shell=True)
# Reset timer
timer = 15 * 60
else:
subprocess.call("sudo /opt/vc/bin/tvservice -o", shell=True)
except KeyboardInterrupt:
print "Quit"
GPIO.cleanup()
To put it in context, I'm using a PIR sensor to detect motion and switch on an hdmi connected monitor on a Raspberry Pi. After 15 mins of no movement I want to switch the monitor off and then if (at a later time) movement is detected, switch it back on again and restart the time.
The description sounds similar to a dead main's switch / watchdog timer. How it is implemented depends on your application: whether there is an event loop, are there blocking functions, do you need a separate process for proper isolation, etc. If no function is blocking in your code:
#!/usr/bin/env python3
import time
from time import time as timer
timeout = 900 # 15 minutes in seconds
countdown = timeout # reset the count
while True:
time.sleep(1 - timer() % 1) # lock with the timer, to avoid drift
countdown -= 1
if should_reset_count():
countdown = timeout # reset the count
if countdown <= 0: # timeout happened
countdown = timeout # reset the count
"some code is executed"
The code assumes that the sleep is never interrupted (note: before Python 3.5, the sleep may be interrupted by a signal). The code also assumes no function takes significant (around a second) time. Otherwise, you should use an explicit deadline instead (the same code structure):
deadline = timer() + timeout # reset
while True:
time.sleep(1 - timer() % 1) # lock with the timer, to avoid drift
if should_reset_count():
deadline = timer() + timeout # reset
if deadline < timer(): # timeout
deadline = timer() + timeout # reset
"some code is executed"
What is the best way to repeatedly execute a function every x seconds in Python?
How to run a function periodically in python
Maybe you should look into the Linux tool cron to schedule the execution of your script.

Creating a timer in python

import time
def timer():
now = time.localtime(time.time())
return now[5]
run = raw_input("Start? > ")
while run == "start":
minutes = 0
current_sec = timer()
#print current_sec
if current_sec == 59:
mins = minutes + 1
print ">>>>>>>>>>>>>>>>>>>>>", mins
I want to create a kind of stopwatch that when minutes reach 20 minutes, brings up a dialog box, The dialog box is not the problem. But my minutes variable does not increment in this code.
See Timer Objects from threading.
How about
from threading import Timer
def timeout():
print("Game over")
# duration is in seconds
t = Timer(20 * 60, timeout)
t.start()
# wait for time completion
t.join()
Should you want pass arguments to the timeout function, you can give them in the timer constructor:
def timeout(foo, bar=None):
print('The arguments were: foo: {}, bar: {}'.format(foo, bar))
t = Timer(20 * 60, timeout, args=['something'], kwargs={'bar': 'else'})
Or you can use functools.partial to create a bound function, or you can pass in an instance-bound method.
You can really simplify this whole program by using time.sleep:
import time
run = raw_input("Start? > ")
mins = 0
# Only run if the user types in "start"
if run == "start":
# Loop until we reach 20 minutes running
while mins != 20:
print(">>>>>>>>>>>>>>>>>>>>> {}".format(mins))
# Sleep for a minute
time.sleep(60)
# Increment the minute total
mins += 1
# Bring up the dialog box here
I'd use a timedelta object.
from datetime import datetime, timedelta
...
period = timedelta(minutes=1)
next_time = datetime.now() + period
minutes = 0
while run == 'start':
if next_time <= datetime.now():
minutes += 1
next_time += period
Your code's perfect except that you must do the following replacement:
minutes += 1 #instead of mins = minutes + 1
or
minutes = minutes + 1 #instead of mins = minutes + 1
but here's another solution to this problem:
def wait(time_in_seconds):
time.sleep(time_in_seconds) #here it would be 1200 seconds (20 mins)
mins = minutes + 1
should be
minutes = minutes + 1
Also,
minutes = 0
needs to be outside of the while loop.
I want to create a kind of stopwatch that when minutes reach 20 minutes, brings up a dialog box.
All you need is to sleep the specified time. time.sleep() takes seconds to sleep, so 20 * 60 is 20 minutes.
import time
run = raw_input("Start? > ")
time.sleep(20 * 60)
your_code_to_bring_up_dialog_box()
# this is kind of timer, stop after the input minute run out.
import time
min=int(input('>>'))
while min>0:
print min
time.sleep(60) # every minute
min-=1 # take one minute
import time
...
def stopwatch(mins):
# complete this whole code in some mins.
time.sleep(60*mins)
...
import time
mintt=input("How many seconds you want to time?:")
timer=int(mintt)
while (timer != 0 ):
timer=timer-1
time.sleep(1)
print(timer)
This work very good to time seconds.
You're probably looking for a Timer object: http://docs.python.org/2/library/threading.html#timer-objects
Try having your while loop like this:
minutes = 0
while run == "start":
current_sec = timer()
#print current_sec
if current_sec == 59:
minutes = minutes + 1
print ">>>>>>>>>>>>>>>>>>>>>", mins
import time
def timer(n):
while n!=0:
n=n-1
time.sleep(n)#time.sleep(seconds) #here you can mention seconds according to your requirement.
print "00 : ",n
timer(30) #here you can change n according to your requirement.
import time
def timer():
now = time.localtime(time.time())
return now[5]
run = raw_input("Start? > ")
while run == "start":
minutes = 0
current_sec = timer()
#print current_sec
if current_sec == 59:
mins = minutes + 1
print ">>>>>>>>>>>>>>>>>>>>>", mins
I was actually looking for a timer myself and your code seems to work, the probable reason for your minutes not being counted is that when you say that
minutes = 0
and then
mins = minutes + 1
it is the same as saying
mins = 0 + 1
I'm betting that every time you print mins it shows you "1" because of what i just explained, "0+1" will always result in "1".
What you have to do first is place your
minutes = 0
declaration outside of your while loop. After that you can delete the
mins = minutes + 1
line because you don't really need another variable in this case, just replace it with
minutes = minutes + 1
That way minutes will start off with a value of "0", receive the new value of "0+1", receive the new value of "1+1", receive the new value of "2+1", etc.
I realize that a lot of people answered it already but i thought it would help out more, learning wise, if you could see where you made a mistake and try to fix it.Hope it helped. Also, thanks for the timer.
from datetime import datetime
now=datetime.now()
Sec=-1
sec=now.strftime("%S")
SEC=0
while True:
SEC=int(SEC)
sec=int(sec)
now=datetime.now()
sec=now.strftime("%S")
if SEC<sec:
Sec+=1
SEC=sec
print(Sec) #the timer is Sec

Categories