Countdown Timer…Don't know where to start

Question:

I am very very new to python and I am trying to make a simple timer app with it.
So if I input a number, like 30, the code should start counting down and output

>>> 30
>>> 29
>>> 28
>>> 27

and so on..

I am trying to get some logic into my brain. I was trying to do this since to days with same code in different places.

import time

x = input("seconds to blast off: ")
for z in range(x):
    timer.sleep(x)
print("blast off")

This is all I have written and I am stuck here.

Asked By: Ash-Ketchum

||

Answers:

Try this:

import time

sec = int(input('No. of seconds: '))
print(sec)

for s in range(sec):
    sec = int(sec) - 1
    time.sleep(1)
    if sec == 0:
        print("Blast Off")
    else:
        print(str(sec))

You got quite close to the solution.
timer.sleep() takes in the number of seconds.
Although, you could have found such answers on the web.

Answered By: Tanmay

There’s a few things here that need a little work.

First, input will always returns a string, so x is also a string. So if the user were to input ’30’, you would run for z in range('30'): which will error. Instead, you should cast x to an int with int(x).

Next, it’s time.sleep, not timer.sleep

The way I’d implement the counter part personally would be to keep track of the start time, then calculate the end time. Then, find the difference between the time in the iteration and the end time and loop while that is greater than 0. It might look like this:

import time

x = int(input('Number of seconds: '))

end = time.time() + x

while end - time.time() > 0:
    print(round(end - time.time()))
    time.sleep(1)
Answered By: Anonymous4045
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.