Python if condition true for x amount of time - python

I would like to create a condition that only gets executed if a is True for more than 3 seconds. I would like it to work like this.
if a == True for more than 3 seconds:
dosomething

If you want to check if the value hasn't change for 3 seconds.
import time
id_a_old = id(a)
time.sleep(3)
id_a_new = id(a)
if id_a_old == id_a_new: # assumes that a is initially true
dosomething
Since bool type is immutable the object id changes if it gets changed.
If you want to check if is has changed after 3 seconds do the following. If any thread changes a within 3 seconds it will capture that.
import time
time.sleep(3)
if a:
dosomething

Simple solution (motivated from Marlon Abeykoon's solution):
import time
startTime = time.time()
while a == True:
endTime = time.time()
#do other stuff
if (endTime - startTime > 3):
print("Longer than 3 seconds")
break

import time
a = True
x = int(time.time())
xa = a
while 1:
if a == True and xa == a and int(time.time()) == x + 3:
# dosomething
print "A is True for 3 seconds"
break
if(xa != a):
# dosomething
print "Value of alfa changed from %s to %s in less than 3 seconds" %(xa, a)
break

Related

python threading.Timer(second, func).start()

import threading
import datetime
def showA():
now = datetime.datetime.utcnow() + datetime.timedelta(hours=9)
now_time = datetime.time(now.hour,now.minute,now.second)
a = 'timer_checking...'
print(f'{a} {now_time}')
second = 5
threading.Timer(second, showA).start()
showA()
This code shows me 'timer_checking.. 11:11:27'
second will add +5 for good.
I want to make showA() operate
first 5 seconds
second 4 seconds
third 3 seconds
fourth 2 seconds
fifth 1 second
second == 0
start again 5 seconds.
please Help me.
timer interval change after per operate, so interval must be an argument.
well, showA create a thread for each operate, thread is costly. showA2 may be better.
import threading
import datetime
# I want to make showA() operate
# first 5 seconds second 4 seconds third 3 seconds fourth 2 seconds fifth 1 second, second == 0 start again 5 seconds.
def loop_interval(old_interval):
if old_interval == 1:
return 5
return old_interval - 1
def showA(interval):
now = datetime.datetime.utcnow() + datetime.timedelta(hours=9)
now_time = datetime.time(now.hour, now.minute, now.second)
a = 'timer_checking...'
print(f'{a} {now_time}')
threading.Timer(interval, showA, args=(loop_interval(interval),)).start()
def showA2():
threading.Thread(target=_show).start()
def _show():
e = threading.Event()
interval = 5
while 1:
e.wait(interval)
now = datetime.datetime.utcnow() + datetime.timedelta(hours=9)
now_time = datetime.time(now.hour, now.minute, now.second)
a = 'timer_checking...'
print(f'{a} {now_time}')
interval = loop_interval(interval)
if __name__ == '__main__':
showA(5)
# showA2()
print(1)

how to fix a random choice generator?

My python game isn't working, the sequences beginning with:
if int(total_time) > 10:
isn't triggering, but when I press D, C or W I am getting the 'you opened something' text though. The code there is right as far as I know, it's just not working. I used the or prevtime to allow you to do it the first time.
import random, time, pygame, sys
from pygame.locals import *
total_time = time.clock()
pygame.init()
XQR_prevtime = 0
ppayh_prevtime = 0
pu_ekaw_prevtime = 0
diff = 1
windowSurface = pygame.display.set_mode((400,400),0,32)
time.sleep(3)
XQR_awakened = False
ppayh_awakened = False
pu_ekaw_awakened = False
if int(total_time) > 10:
if int(XQR_prevtime) > (12 - diff) or int(XQR_prevtime) == 0 or XQR_awakened == True:
if XQR_awakened == True:
print("You left something open...")
time.sleep(2)
print("And a mystery came in")
time.sleep(2)
sys.exit()
if random.randint(0,diff) == 1:
print(3)
XQR_prevtime = time.clock()
door_opening.play()
XQR_awakened = True
if int(ppayh_prevtime) > (12 - diff) or int(ppayh_prevtime) == 0 or ppayh_awakened == True:
if ppayh_awakened == True:
print("You left something open...")
time.sleep(2)
print("And a friend came in")
time.sleep(2)
sys.exit()
if randint(0,diff) == 1:
print(3)
ppayh_prevtime = time.clock()
closet_opening.play()
ppayh_awakened = True
if int(pu_ekaw_prevtime) > (12 - diff) or int(pu_ekaw_prevtime) == 0 or pu_ekaw_prevtime == True:
if ekaw_up_awakened == True:
print("You left something open...")
time.sleep(2)
print("And an answer came in")
time.sleep(2)
sys.exit()
if randint(0,diff) == 1:
print(3)
pu_ekaw_prevtime = time.clock()
window_opening.play()
pu_ekaw_awakened = True
total_time never changes, so you can never reach your condition.
The line
total_time = time.clock()
assigns a numeric value (a float) to total_time. There is no reference back to the time.clock() function, the function returns just a normal float object, not a timer object.
And normal float values don't change, they are immutable. The total_time value is not going to change as you game runs.
If you want to measure elapsed time, just keep calling time.clock():
if time.clock() > 10:
You don't need to convert a float value to int here, comparisons with integers just work.

printing out letter every min Python

so i am trying to figure this out for school. Im trying to print x out every minute and every ten min it will print on a new line. so far i cant get the "printing x" every min down. can someone please help.
this is my code
import time;
inTime = float(input("type in how many second"))
oldTime = time.time()-inTime
print (time.time())
def tenMin(oldTime):
newTime = time.time()
if ((newTime - oldTime)>= 25):
return True
else:
False
while (True):
if (tenMin==True):
print ("x")
newTime = time.time()
oldtime = time.time()
else:
oldTime = time.time()
continue
Your first problem is in the line
if (tenMin==True):
You compare a function reference to a boolean, clearly the answer would be False. You have to pass a parameter
if (tenMIn(oldTime)):
...
First you have some issues with you code:
else:
False - This is not true syntax in python.
If you want timer, why are you asking the user for input?
You have a logic problem:
inTime = float(input("type in how many second"))
oldTime = time.time()-inTime
time.time is float yes, but can a user really know what to print in UnixTime?
I'll suggest a simple solution it's not the very best but it works.
It will print "x" every 1 Min and after 10 Min it will print "\n" (new line)
import time
def main():
#both timers are at the same start point
startTimerTen = time.time()
startTimerMin = startTimerTen
while True:
getCurrentTime = time.time()
if getCurrentTime - startTimerTen >= 600:
# restart both parameters
startTimerTen = getCurrentTime
startTimerMin = getCurrentTime
print "This in 10 min!\n"
if getCurrentTime - startTimerMin >= 60:
# restart only min parameter
startTimerMin = getCurrentTime
print "x"
#end of main
if __name__ == "__main__":
main()

clock countdown calculation in python

I want to write a function called boom(h,m,s) that after input from main starts printing in HH:MM:SS format the countdown clock, and then prints "boom".
I'm not allowed to use existing modules except the time.sleep(), so I have to base on While\For loops.
import time
def boom(h,m,s):
while h>0:
while m>0:
while s>0:
print ("%d:%d:%d"%(h,m,s))
time.sleep(1)
s-=1
print ("%d:%d:%d"%(h,m,s))
time.sleep(1)
s=59
m-=1
print ("%d:%d:%d"%(h,m,s))
time.sleep(1)
s=59
m=59
h-=1
while h==0:
while m==0:
while s>0:
print ("%d:%d:%d"%(h,m,s))
time.sleep(1)
s-=1
print ("BooM!!")
I figured how to calculate the seconds part, but when I input zeros on H and M parameters, it's messing with the clock.
The problem is here:
while h==0:
while m==0:
while s>0:
If m == 0, and s == 0 the while loop doesn't break, so there is an infinite loop.
Just add an else clause to the (last and) inner-most while, like so:
while s>0:
...
else: # executed once the above condition is False.
print ('BooM!!')
return # no need to break out of all the whiles!!
just convert it all to seconds and convert it back when you print ...
def hmsToSecs(h,m,s):
return h*3600 + m*60 + s
def secsToHms(secs):
hours = secs//3600
secs -= hours*3600
mins = secs//60
secs -= mins*60
return hours,mins,secs
def countdown(h,m,s):
seconds = hmsToSecs(h,m,s)
while seconds > 0:
print "%02d:%02d:%02d"%secsToHms(seconds)
seconds -= 1
sleep(1)
print "Done!"

Python timer countdown

I want to know about timer in Python.
Suppose i have a code snippet something like:
def abc()
print 'Hi'
print 'Hello'
print 'Hai'
And i want to print it every 1 second. Max three times;ie; 1st second i need to check the printf, 2nd second I need to check as well in 3rd second.
In my actual code variables value will be updated.
I need to capture at what second all the variables are getting updated.
Can anybody tell me how to do this.
time.sleep is fine in this case but what if the abc() function takes half a second to execute? Or 5 minutes?
In this case you should use a Timer object.
from threading import Timer
def abc():
print 'Hi'
print 'Hello'
print 'Hai'
for i in xrange(3):
Timer(i, abc).start()
Use time.sleep.
import time
def abc():
print 'Hi'
print 'Hello'
print 'Hai'
for i in xrange(3):
time.sleep(1)
abc()
You should look into time.sleep(). For example:
for i in xrange(5):
abc()
time.sleep(3)
That will print your lines 5 times with a 3 second delay between.
import time
def abc()
for i in range(3):
print 'Hi'
print 'Hello'
print 'Hai'
time.sleep(1)
import time
def abc():
print 'Hi'
print 'Hello'
print 'Hai'
for i in range(3):
time.sleep(3-i)
abc()
usually for me this works...
import time
def abc():
print 'Hi'
time.sleep(1)
print 'Hello'
time.sleep(1)
print 'Hai'
time.sleep(1)
I think you can guess after that...
import sys
import time
c=':'
sec = 0
min = 0
hour = 0
#count up clock
while True:
for y in range(59): #hours
for x in range (59): #min
sec = sec+1
sec1 = ('%02.f' % sec) #format
min1 = ('%02.f' % min)
hour1= ('%02.f' % hour)
sys.stdout.write('\r'+str(hour1)+c+str(min1)+c+str(sec1)) #clear and write
time.sleep(1)
sec = 0
sys.stdout.write('\r' + str(hour1) + c + str(min1) + c + '00') #ensure proper timing and display
time.sleep(1)
min=min+1
min = 0
sys.stdout.write('\r' + str(hour1) + c + str(min1) + c + '00') #ensure proper timing and display
time.sleep(1)
hour=hour+1

Categories