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!"
Related
My code:
def timer():
while True:
try:
when_to_stop = 90
except KeyboardInterrupt:
break
except:
print("error, please star game again")
while when_to_stop > 0:
m, s = divmod(when_to_stop, 60)
h, m = divmod(m, 60)
time_left = str(h).zfill(2) + ":" + str(m).zfill(2) + ":" +
str(s).zfill(2) # got cut off, belongs to the line before this
print("time:", time_left + "\r", end="")
if time_left == 0:
print("TIME IS UP!")
time.sleep(1)
when_to_stop -= 1
This works perfectly fine, except that time.sleep means my whole program sleeps, so anything after that while stop for 90 seconds. Any way to fix that?(or make a new timer without time.sleep?)
I think that, alternatively, you could keep track of when the timer starts, and check the time by seeing if the time that's passed is longer than the timer is supposed to last. I'm not sure how much you know about classes and objects in Python, but here is the solution that came to mind:
import datetime
class Timer:
def __init__(self,**kwargs):
self.start = datetime.datetime.now()
self.length = datetime.timedelta(**kwargs)
self.end = self.start+self.length
def isDone(self):
return (self.end-datetime.datetime.now()).total_seconds()<=0
def timeLeft(self):
return self.end-datetime.datetime.now()
def timeElapsed(self):
return datetime.datetime.now()-self.start
Even if you don't quite understand the class itself, if you put it in your code it should work like a charm:
#This has the same options as:
#class datetime.timedelta(days, seconds, microseconds, milliseconds, minutes, hours, weeks)
t = Timer(days=2)
while(not t.isDone()):
#Do other game stuff here....
time_left = t.timeLeft()
print(f"time: {time_left}")
#And here....
print("Done now")
Who can help me on this?
Pause Countdown when press "P" Key and continue the Countdown when press "S" key. Until now i have this code, but i cant find the way to solve this.
Thanks
from multiprocessing import Process
import keyboard
import time
def countdown_1():
i=6
j=40
k=0
while True:
a = keyboard.read_key()
if(str(a) != "p"):
if(j==-1):
j=59
i -=1
if(j > 9):
print(str(k)+str(i)+":"+str(j))
else:
print(str(k)+str(i)+":"+str(k)+str(j))
time.sleep(1)
j -= 1
if(i==0 and j==-1):
break
if(i==0 and j==-1):
print("END")
time.sleep(1)
countdown_1()
I get a solution to your problem, that is because when you use keyboard.readkey() python wait for a key to be pressed. instead, you should use keyboard.is_pressed('X')
I have modified your code to make a working version, I slightly change it to match my taste.
from multiprocessing import Process
import keyboard
import time
def countdown_1():
pause_keyboard = False # I use a bolean as a state is clearer for me
i = 6 # minutes
j = 40
k = 0 # represent 0 we will instead use code format
while True:
starting_time = time.time()
while True: # this loop wait one second or slightly more
if time.time() - starting_time >= 1: # a second or more
break
if keyboard.is_pressed('p'):
pause_keyboard = True
elif keyboard.is_pressed('s'):
pause_keyboard = False
if pause_keyboard:
continue
if (j == -1): ## here we adjust the count when we changes minutes
j = 59 # 59 secondes
i -= 1 # one minutes less
if(j > 9): ## in order to pretty print
print("{}{}:{}".format(0, i, j)) # you can direclty use 0 instead of k.
else:
print("{}{}:{}{}".format(0, i, 0, j))
j -= 1
if(i==0 and j==-1): # we finish the counter
break
if(i==0 and j==-1):
print("END")
time.sleep(1) # wait a last second
countdown_1()
EDIT: Use time.time() instead of sleep to be able to catch signals.
I'm looking for a way to return to a while loop after it is done.
Basically, in my main code, at the beginning, there is a while loop that I want to do for x amount of times and then exit out and execute some other code. If certain values are met, return to the while loop at the top of the main.
Here is the code that I wrote but once the while loop is finished it just stops.
t = 0
def main():
global t
try:
while t < 3:
distance = Tank_Measurement()
if distance > 5 and distance < 100:
print ('Distance:',distance ,'cm')
Pumping_to_Growbed()
time.sleep(2)
draining_Selenoid()
t = t + 1
else:
print ('Distance:',distance ,'cm is out of range')
time.sleep(1)
Tank_Measurement()
t = t + 1
return
distance = Tank_Measurement()
distance2 = growbed_Measurement()
if distance < 5 and distance2 < 5:
print ('Water level in main tank low')
print ('Filling up main tank')
time.sleep(1)
Pumping_to_mainTank()
t = 0
else:
t = 0
except KeyboardInterrupt:
print ('Exiting program gracefully')
for i in range(3,0,-1):
time.sleep(1)
sys.stdout.write(str(i)+' ')
sys.stdout.flush()
finally:
GPIO.cleanup()
main()
Put the entire body of main() inside another another while loop:
def main():
keep_looping = True
while keep_looping:
... original code here
if some_condition:
keep_looping = False
once the while loop is finished it just stops
That is because you have a return as the next statement after while. So it returns to the point where you called main(), which then is the last line of your code, no further statements or code after that.
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()
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