How To Create a Countdown Timer Using Python?

I help you create a countdown timer using Python! In this tutorial, we’ll be using the time module to create a simple countdown timer that counts down from a specified number of seconds. Here's the step-by-step guide:
Step 1: Import the time Module
The time module in Python provides functions for working with time-related tasks. We'll use it to add delays to our countdown timer.
import timeStep 2: Define the Countdown Function
Create a function that takes the total number of seconds as an argument and counts down from that value.
def countdown_timer(seconds):
while seconds > 0:
print(f"Time remaining: {seconds} seconds")
time.sleep(1) # Delay for 1 second
seconds -= 1
print("Time's up!")Step 3: Get User Input and Start the Countdown
Ask the user to input the number of seconds they want to set for the countdown timer and call the countdown_timer function.
def main():
try:
seconds = int(input("Enter the countdown time in seconds: "))
countdown_timer(seconds)
except ValueError:
print("Invalid input. Please enter a valid number of seconds.")
if __name__ == "__main__":
main()Step 4: Run the Countdown Timer
Run the script, input the desired countdown time in seconds, and watch the countdown happen!
Full Code:
import time
def countdown_timer(seconds):
while seconds > 0:
print(f"Time remaining: {seconds} seconds")
time.sleep(1) # Delay for 1 second
seconds -= 1
print("Time's up!")
def main():
try:
seconds = int(input("Enter the countdown time in seconds: "))
countdown_timer(seconds)
except ValueError:
print("Invalid input. Please enter a valid number of seconds.")
if __name__ == "__main__":
main()Usage:
- Run the script using a Python interpreter.
- Enter the desired countdown time in seconds.
- Watch the countdown timer in action!
Feel free to customize the code to your liking. You could add more features, like sound alerts when the timer finishes, or you could incorporate this countdown timer into a larger program. Enjoy experimenting with your countdown timer implementation!
Buy me a Coffee: https://bmc.link/sarahdev
Access to my private Github: bit.ly/3KDPw6G
(With all the source code from my various projects posted on Medium, you’ll find source code previews and so much more )
