I need a function to start a countdown from 3, and then run a program once the countdown is complete, I can't use the time.sleep() as that particular function won't start the program.
Currently, my function counts up from zero, and also prints multiple iterations of the same number.
I also feel like the function is overcomplicated, are there any simpler methods?
Code:
def countdown():
countdown_time = 3
start_time = time.time()
while (time.time() - start_time) < countdown_time:
print(round(time.time() - start_time))
if (time.time() - start_time) >= countdown_time:
break
Ideally it should just print:
3
2
1
But it prints something more like this:
1
1
1
2
2
2
3
3
3
CodePudding user response:
I think this what you are looking for:
from time import sleep
def countDown():
for i in range(3, 0, -1):
print(i)
sleep(1)
countDown()
You are saying that you can't use the time.sleep()
as that particular function won't start the program which is wrong. It works here just fine.
CodePudding user response:
This works:
import time
def countdown():
countdown_time = 3
start_time = time.time()
while countdown_time > 0:
if countdown_time - round(time.time() - start_time) <= countdown_time and countdown_time != 0:
print(countdown_time)
countdown_time -= 1
countdown()
Output:
3
2
1