Python Program - Create a Countdown Timer

w‮figi.ww‬tidea.com

here's a Python program that creates a countdown timer:

import time

# get the countdown time from user
countdown_time = int(input("Enter countdown time in seconds: "))

# start the countdown
while countdown_time:
    mins, secs = divmod(countdown_time, 60)
    time_str = "{:02d}:{:02d}".format(mins, secs)
    print(time_str, end="\r")
    time.sleep(1)
    countdown_time -= 1

# print a message when the countdown is finished
print("Time's up!")

In this program, we first import the time module using the import keyword.

We then use the input() function to get the countdown time from the user, and store it in the variable countdown_time. Note that we convert the input to an integer using the int() function.

We then start a while loop that continues until the countdown time reaches zero. Inside the loop, we use the divmod() function to calculate the number of minutes and seconds remaining in the countdown, and format the result as a string with two digits for the minutes and seconds using the str.format() method.

We then use the print() function to print out the formatted time string, followed by the special character \r to return the cursor to the beginning of the line. This allows us to overwrite the previous time string with the new one.

We then use the time.sleep() function to pause the program for one second, and subtract one second from the countdown time.

Once the countdown reaches zero, the while loop ends and we print out a message using the print() function to indicate that the countdown is finished.