Introduction: A countdown timer is a basic yet useful application that helps track the passage of time by counting down from a given number of seconds. It’s commonly used in scenarios such as timers for cooking, setting reminders, or managing time in tasks. In this program, we will create a countdown timer in Python that takes an input in seconds and counts down to zero.
Objective: The goal of this program is to implement a countdown timer in Python that displays the remaining time every second and stops once it reaches zero. This simple task can help understand the concepts of time manipulation, loops, and user input in Python.
Python Code for Countdown Timer
import time
# Function to implement countdown timer
def countdown_timer(seconds):
while seconds > 0:
mins, secs = divmod(seconds, 60)
timeformat = '{:02d}:{:02d}'.format(mins, secs)
print(f"Time remaining: {timeformat}", end="\r")
time.sleep(1)
seconds -= 1
print("Time's up! ")
# User input for the countdown time in seconds
try:
total_seconds = int(input("Enter the time in seconds for the countdown: "))
print("\nCountdown starting...\n")
countdown_timer(total_seconds)
except ValueError:
print("Please enter a valid number of seconds.")
Explanation of the Program:
The program starts by defining a function countdown_timer
that accepts the number of seconds to count down. It then enters a while
loop that continues until the timer reaches zero. Inside the loop, it calculates minutes and seconds from the total seconds using divmod()
, formats the result into a string with two digits for both minutes and seconds, and then prints it. The time.sleep(1)
function pauses the execution for one second, simulating a real-time countdown.
The input()
function is used to ask the user to enter the number of seconds they want to countdown from. If the user enters a non-integer value, the program catches it using a try-except
block and prompts the user to enter a valid number.
How to Run the Program:
- Ensure that Python is installed on your system. You can download it from here.
- Open a text editor (like Notepad, Visual Studio Code, or PyCharm) and paste the code into a new file.
- Save the file with a
.py
extension, for example,countdown_timer.py
. - Open a terminal (or command prompt) and navigate to the folder where the file is saved.
- Type
python countdown_timer.py
to run the program.
Copyright Information:
© 2024 Learn Programming. All Rights Reserved.