Project Overview 💡
In this project, you'll build a countdown timer using Python's time
module. The user enters a number of seconds, and the program counts down to zero, updating every second in the terminal. This is a great example of loops, formatting output, and working with time-based functions.
Challenge Yourself! 🚀
Before checking the solution, try creating a script that takes a number of seconds and counts down to zero, displaying the time left.
Task:
Write a Python program that:
Asks the user to input a duration in seconds
Displays a countdown timer in mm:ss format
Prints a message when the timer is done
Expected Output: The program will ask the user to enter a value for seconds (e.g., 10):
After the user enters the seconds, the program will print out the time every second and then print out “Time’s up!” at the end.
Give it a shot! Scroll down when you're ready for the step-by-step guide.
Spoiler Alert!
Step-by-Step Guide
Step 1️⃣: Import the time
Module
This module allows us to pause the program for one second between countdown ticks.
import time
Step 2️⃣: Define the Countdown Function
Create a function that takes seconds as input and displays the time countdown.
def countdown_timer(seconds):
while seconds:
mins, secs = divmod(seconds, 60)
timer = f'{mins:02d}:{secs:02d}'
print(timer, end="\r")
time.sleep(1)
seconds -= 1
print("Time's up!")
Step 3️⃣: Get User Input
Prompt the user to enter the number of seconds to count down.
time_in_seconds = int(input("Enter the time in seconds: "))
Step 4️⃣: Start the Countdown
Call the countdown function with the user's input.
countdown_timer(time_in_seconds)
Complete Code 🧨
import time
def countdown_timer(seconds):
while seconds:
mins, secs = divmod(seconds, 60)
timer = f'{mins:02d}:{secs:02d}'
print(timer, end="\r")
time.sleep(1)
seconds -= 1
print("Time's up!")
# Ask the user for the countdown time in seconds
time_in_seconds = int(input("Enter the time in seconds: "))
countdown_timer(time_in_seconds)
Alternative Solution
Here’s a version that clears the terminal each second instead of overwriting the line:
import time
import os
def countdown_timer(seconds):
while seconds:
mins, secs = divmod(seconds, 60)
print(f"{mins:02d}:{secs:02d}")
time.sleep(1)
os.system('cls' if os.name == 'nt' else 'clear')
seconds -= 1
print("Time's up!")
seconds = int(input("Enter time in seconds: "))
countdown_timer(seconds)
Comparison
The original version uses
end="\r"
to overwrite the same line in the terminal.The alternative version clears the screen every second, which may be more visually pleasing in some terminals.
Want More? 🔥
Enjoyed this project? Unlock real-world projects with full guides & solutions by subscribing to the paid plan. 🎉
TERM environment variable not set. how would i go about fixing this ? i created a new folder in created a main file, place the code in the output im getting 'TERM environment variable not set.' this as a output