How to make a countdown program in python - python

I am trying to create a countdown in python and I want very simple way of creating that. I watched a couple of videos but couldn't find a right solution for it.
This is the code which I am using right now.
import time
def countdown(t):
while t:
mins, secs = divmod(t, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print(timer, end="\r")
time.sleep(1)
t -= 1
print('Time Over!!!!')
t = input("Enter the time in seconds: ")
countdown(int(t))

The problem is that when you sleep for 1 second, it will not be for exactly 1 second and theoretically over long enough time the errors could propagate enough such that you could conceivably be printing out an incorrect time. To correct this, your code needs to actually check in its loop how much time has actually elapsed since the start of the program running and use that to compute what the new value of t is, and it should do this frequently so that the countdown is smooth. For example:
import time
def countdown(t):
start_time = time.time()
start_t = t
# compute accurate new t value aprroximately every .05 seconds:
while t > 0:
mins, secs = divmod(t, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print(timer, end="\r")
time.sleep(.05) # finer timing
now = time.time()
elapsed_time = int(now - start_time) # truncated to seconds
t = start_t - elapsed_time
print('Time Over!!!!')
t = input("Enter the time in seconds: ")
countdown(int(t))

Related

Create clock pulse with python

I want to work with exactly 20ms sleep time. When i was using time.sleep(0.02), i am facing many problems. It is not working what i want. If I had to give an example;
import time
i = 0
end = time.time() + 10
while time.time() < end:
i += 1
time.sleep(0.02)
print(i)
We wait to see "500" in console. But it is like "320". It is a huge difference. Because sleep time is not working true and small deviations occur every sleep time. It is increasing cumulatively and we are seeing wrong result.
And then, i want to create my new project for clock pulse. Is it that possible with time.time()?
import time
first_time = time.time() * 100 #convert seconds to 10 * miliseconds
first_time = int(first_time) #convert integer
first_if = first_time
second_if = first_time + 2 #for sleep 20ms
third_if = first_time + 4 #for sleep 40ms
fourth_if = first_time + 6 #for sleep 60ms
fifth_if = first_time + 8 #for sleep 80ms
end = time.time() + 8
i = 0
while time.time() < end:
now = time.time() * 100 #convert seconds to 10 * miliseconds
now = int(now) #convert integer
if i == 0 and (now == first_if or now > first_if):
print('1_' + str(now))
i = 1
if i == 1 and (now == second_if or now > second_if):
print('2_' + str(now))
i = 2
if i == 2 and (now == third_if or now > third_if):
print('3_' + str(now))
i = 3
if i == 3 and (now == fourth_if or now > fourth_if):
print('4_' + str(now))
i = 4
if i == 4 and (now == fifth_if or now > fifth_if):
print('5_' + str(now))
break
Out >> 1_163255259009
2_163255259011
3_163255259013
4_163255259015
5_163255259017
Is this project true logic? And If it is true logic, how can finish this projects with true loops?
Because i want these sleeps to happen all the time. Thank you in advice.
Let's say you want to count in increments of 20ms. You need to sleep for the portion of the loop that's not the comparison, increment, and print. Those operations take time, probably about 10ms based on your findings.
If you want to do it in a loop, you can't hard code all the possible end times. You need to do something more general, like taking a remainder.
Start with the time before the loop:
t0 = time.time()
while time.time() < end:
i += 1
Now you need to figure out how long to sleep so that the time between t0 and the end of the sleep is a multiple of 20ms.
(time.time() - t0) % 0.02 tells you how far past a 20ms increment you are because python conveniently supports floating point modulo. The amount of time to wait is then
time.sleep(0.02 - (time.time() - t0) % 0.02)
print(i)
Using sign rules of %, you can reduce the calculation to
time.sleep(-(time.time() - t0) % 0.02)

Python countdown not line by line

so i tried to create a countdown in python. It works fine, but I want to have a better print output. At the moment it prints the remaining time line by line, so my output is overfilled after some time. I then tried to do:
import time
def countdown(t):
while t:
print(t, end="\r")
time.sleep(1)
t -= 1
print('finished')
countdown(60)
but it outputs for me:
5
4
3
2
1
finished
I'd like to have it that it prints the countdown and the finished all in one line and deletes the number before it...
Thanks for helping :)
Here's what it should look like:
But i dont need the 00:00 format, the seconds are fine for me
almost there, below code will print your timer value side by side. not sure what 'deletes the number before it.' is!
import time
def countdown(t):
while t:
print(t, end=" ")
time.sleep(1)
t -= 1
print('finished')
countdown(60)
Delete the previous character using '\b'
import time
def countdown(t):
# how many digits
digits = int(t / 10) + 1
while t:
print('\b{}'.format(str(t).zfill(digits)), end="\r")
time.sleep(1)
t -= 1
print('finished')
countdown(10)
The following will work if called from Windows CMD
import time, sys, os
def pretty_format(seconds):
seconds = seconds % (24 * 3600)
hour = seconds // 3600
seconds %= 3600
minutes = seconds // 60
seconds %= 60
# Here's the formatting you asked for! 00:00:59 etc...
return "%d:%02d:%02d" % (hour, minutes, seconds)
def count_down(seconds):
os.system("cls") # Windows -> clear the cmd screen
while seconds:
sys.stdout.write("{}{}".format(pretty_format(seconds), "\b"*100)) # \b replaces the previous value. if we have a bunch of values we need to do multiple \b. Here's 100!
time.sleep(1)
seconds -=1
print('finished')
count_down(60)

For Loop executed every 5 minutes for 24 hours

I have a for loop and I want each iteration to be executed every 5 minutes. Essentially, I want to freeze/sleep the loop for 5 minutes and then continue from where it left 5 minutes ago, NOT to start from the beginning. In total, I want to do this for an entire day (24hours).
Something like this? The loop runs for (a little more than) twenty-four hours and sleeps for five minutes after each iteration.
from time import sleep, time
ONE_DAY = 24 * 60 * 60 # seconds
FIVE_MINUTES = 5 * 60 # seconds
start_time = time()
current_time = start_time
while current_time <= start_time + ONE_DAY - FIVE MINUTES:
# Do something loopy here...
time.sleep(FIVE_MINUTES)
current_time = time()
You could define a method that simply calls sleep for 5 minutes and then call that in your loop. Kind of like this
import time
# main loop
for i in .....:
# do your stuff
wait5Mins()
# continue doing stuff
def wait5Mins():
time.sleep(300)

Resetting time.clock() in Python

import time
start = time.clock()
while True:
elapsed = (time.clock() - start)
if elapsed > 10:
print("MOTION")
elapsed = 0
I start a timer, calculate elapsed time, and if 10 seconds have passed, I display "MOTION" and then reset elapsed to 0 so "MOTION" only displays every 10 seconds. For some reason, it doesn't work: MOTION does initially get displayed after 10 seconds, but after that, it keeps getting displayed on every iteration.
What did I do wrong?
You have two options; your code doesn't work because you are trying to reset the clock but instead you reset elapsed, which does nothing.
Using modulo division.
start = time.clock()
while True:
elapsed = (time.clock() - start)
if int(elapsed) % 10:
print("MOTION")
Resetting the clock.
start = time.clock()
while True:
elapsed = (time.clock() - start)
if elapsed >= 10:
print("MOTION")
start = time.clock()
You neglected to reset your reference time: change the basis, not the interval. On each iteration, you reset elapsed to 0, but then immediately go back to the original start time. Change the last line of you loop:
start = time.clock()
while True:
elapsed = (time.clock() - start)
if elapsed > 10:
print("MOTION")
start = time.clock()

Timing a Python program using time.clock() vs. time.time() [duplicate]

This question already has answers here:
Python's time.clock() vs. time.time() accuracy?
(16 answers)
Closed 6 years ago.
I am new to Python programming. I started working on Project Euler this morning and I wanted to find out how long it takes to execute my solution. I have searched online for a solution to my
import time
class Solution(object):
def fibonacci(self,limit):
sum = 0
current = 1
next = 2
while(current <= limit):
if current % 2==0:
sum += current
current, next = next, current + next
return str(sum)
if __name__ == "__main__":
start = time.clock()
solution = Solution().fibonacci(4000000)
elapsed = time.clock()-start
print("Solution: %s"%(solution))
print("Time: %s seconds"%(elapsed))
Output:
Solution: 4613732
Time: 2.006085436846098e-05 seconds
import time
class Solution(object):
def fibonacci(self,limit):
sum = 0
current = 1
next = 2
while(current <= limit):
if current % 2==0:
sum += current
current, next = next, current + next
return str(sum)
if __name__ == "__main__":
start = time.time()
solution = Solution().fibonacci(4000000)
elapsed = time.time()-start
print("Solution: %s"%(solution))
print("Time: %s seconds"%(elapsed))
Output:
Solution: 4613732
Time: 0.0 seconds
My question is
Is the time calculated above correct?
What is the difference between time.time() vs time.clock(). If I use time.time() I get 0.0 as time.
In the Python time module, time.clock() measures the time since the first call of the function in seconds, and time.time() measures the time since January 1st, 1970, in seconds.
time.clock() is generally more precise, so using this is what I recommend. This is the reason why you have the tiny result in the first example, rounded down to zero in the second example.

Categories

Resources