[Copy-Paste Ready] Let's Build a Timer App with Python! (Using the time module)
"Where do I even start with programming?" "I try to read books, but I just get discouraged by all the errors..."
Just a few months ago, I felt the exact same way. I started from zero knowledge, and through trial and error with the help of AI, I've now managed to launch two websites on my own.
In this article, my main goal is to have you, as a fellow beginner, experience the joy of making something that "works" from the exact same perspective. This time, we'll use Python's built-in "time wizard," the `time` module, to create a surprisingly simple timer and alarm app.
Let's save the complicated theory for later! First, just copy, paste, and enjoy the moment your computer transforms into a timer!
Step 1: Experience It First! A Super Simple Program That Just Waits 3 Seconds
Seeing is believing. First, let's run the world's simplest timer, which just asks the computer to "wait for 3 seconds." Copy the code below and run it in your Python environment.
# The magic spell to use "time magic"
import time
print("Starting the timer.")
# Pause the program's execution for 3 seconds
time.sleep(3)
print("3 seconds have passed! Great work.")
When you run it, "Starting the timer." should appear, and after a short pause, "3 seconds have passed!" will be displayed. That's it! This is the fundamental basis of a timer.
- `import time`: This is an incantation to tell Python, "I'm going to use time functions now!" It loads a toolbox named `time` that is filled with various time-related magic (functions).
- `time.sleep(3)`: This is the heart of the timer. It's a magic spell called `sleep` from the `time` toolbox, which temporarily stops the program's execution for the number of seconds specified in the parentheses.
What do you think? Isn't it much easier than you expected? This is the experience of making something "work." This small success is the best fuel to keep you going in your programming journey.
Step 2: Make It Your Own! Let's Set the Seconds Freely
A fixed 3-second timer is nice, but it would be great to set any time you want for things like cooking or studying. Next, let's modify the program to ask "How many seconds should I wait?" every time it runs.
This is where the magic spell `input()`, which accepts text input from the user, comes in.
import time
# Receive user input with input()
input_seconds_str = input("In how many seconds should I notify you? Please enter a number: ")
# [IMPORTANT POINT!] Convert the input "string" to an "integer"
seconds = int(input_seconds_str)
print(f"Timer set for {seconds} seconds.")
time.sleep(seconds)
print(f"{seconds} seconds have passed! Time's up!")
When you run this, the program will pause and a cursor will start blinking. Try typing your desired number of seconds (e.g., `10`) and press Enter. The message will appear after waiting for the number of seconds you entered.
⚠️ The Trap Every Beginner Falls Into: `input()` is Always a "String"
Let me share a crucial point where I first stumbled. The rule is that anything received by `input()`, even if you type a number, is treated as a "string".
`time.sleep()` only accepts a number of seconds. If you try to pass it the "string" `"10"`, it will get angry and throw an error, saying, "That's not a number!"
That's why the line `seconds = int(input_seconds_str)` is necessary. This is the process of transforming the string into an "integer" that the computer can work with by wrapping it in the `int()` spell. This "type conversion" is a fundamental and vital concept that appears in all aspects of programming, so please remember it!
Step 3: Make It Look Cool! Implementing a Countdown Feature
Don't you get anxious wondering if the timer is actually running while it's active? Let's add a countdown feature that shows the remaining time so you know "how many seconds are left."
Here we'll use the "repetition" magic, the `for` loop. We'll also use a little trick to keep the display on a single line so that only the numbers appear to update.
import time
seconds = 10 # Fixed at 10 seconds for clarity
# Loop from 10 down to 1, decrementing by 1
for i in range(seconds, 0, -1):
# Display neatly with an f-string. end="\r" is the magic spell!
print(f"Time remaining: {i} sec", end="\r")
# Wait for 1 second
time.sleep(1)
# Message after the countdown finishes
# The key is to add spaces at the end to clear the previous line
print("Time is up! ")
Go ahead and run it. How was it? You should have seen the numbers decrease `10, 9, 8...` in the same spot on your terminal. It looks just like a real timer app, doesn't it!
- `for i in range(seconds, 0, -1):`: Using `range(start, stop, step)`, we create a loop that "starts from `seconds` (10), until it reaches 1 (0 is not included), while decrementing by -1." The count for each iteration (10, 9, 8...) is automatically stored in the variable `i`.
- `print(..., end="\r")`: This is our key technique this time. Normally, `print` adds a new line after displaying text, but adding `end="\r"` changes its behavior to "return the cursor to the beginning of the line without a new line." This causes the next `print` to overwrite the previous display, making it look as if only the numbers are changing.
Step 4: It's Finally Complete! A Real Timer That Plays an Alarm Sound
We're at the final step. Let's add an alarm feature that not only displays a message when the time is up but also notifies you with an actual "sound."
No special libraries are needed. Most computers (and their terminals) have a sort of hidden feature where they play a "beep" sound when a specific "special character" is printed. That character is `\a`.
Here is the final version of the code, incorporating all the features so far, plus error handling for when the user enters something other than a number!
# Import the time module
import time
# Use a try...except block to wrap code that might cause an error
try:
# Get the wait time in seconds from the user
input_seconds_str = input("In how many seconds should the alarm sound? Please enter a number: ")
# Convert the input string to an integer (int type)
seconds = int(input_seconds_str)
print(f"Starting a {seconds}-second countdown.")
# Loop from the specified number of seconds down to 1
for i in range(seconds, 0, -1):
# Use an f-string for a clean display of the remaining time
# end="\r" makes the next print overwrite the current line
print(f"Time remaining: {i} sec ", end="\r")
# Wait for 1 second
time.sleep(1)
# When the loop finishes (time is up), display a message
# \a is the terminal's alert character that plays a bell sound
print("Time's up! The alarm is ringing! \a")
except ValueError:
# Handle the case where non-numeric input is given (int() fails)
print("Error: Please enter a valid number.")
except KeyboardInterrupt:
# Handle the case where the user interrupts the program with Ctrl+C
print("\nTimer interrupted.")
With this, your computer now functions as a complete timer and alarm app. It's also a bit smarter, as it will properly display an error message and exit if you enter non-numeric characters (like `abc`).
Note: The beep sound from `\a` may not play depending on your OS or terminal settings. Even if you don't hear a sound, rest assured that the program is working correctly.
Conclusion: A Small "It Worked!" Moment is a Great Power for the Future
Great job! In this article, you experienced how you can create a practical timer app just by combining the basic features of Python's `time` module.
- Make the program wait with `time.sleep()`
- Receive user instructions with `input()`
- Convert strings to numbers with `int()` (Super important!)
- Repeat processes with a `for` loop
- Make the display look cool with `print(end="\r")`
- Play an alarm sound with `\a`
- Prepare for errors with `try...except`
Each feature is simple on its own, but the fun of programming is that by combining them, you can create a tool that is genuinely useful to someone. The small success you experienced today—"It worked with a copy-paste!" or "I was able to modify it myself!"—will be your greatest motivation as you go on to create more complex and interesting things.
Feel free to use this code as a base to play around with it, like modifying it to accept input in minutes or trying to build a Pomodoro timer (25 minutes of work + 5 minutes of break)!
[Bonus] HTML to Experience All the Code from This Article
You can copy the final Python code introduced in this article from the code block below, save it to your PC with a name like `timer.py`, and run it anytime to try it out. Go ahead and run it on your computer!
<!-- Save as timer.py and run it -->
# Import the time module
import time
# Use a try...except block to wrap code that might cause an error
try:
# Get the wait time in seconds from the user
input_seconds_str = input("In how many seconds should the alarm sound? Please enter a number: ")
# Convert the input string to an integer (int type)
seconds = int(input_seconds_str)
print(f"Starting a {seconds}-second countdown.")
# Loop from the specified number of seconds down to 1
for i in range(seconds, 0, -1):
# Use an f-string for a clean display of the remaining time
# end="\r" makes the next print overwrite the current line
print(f"Time remaining: {i} sec ", end="\r")
# Wait for 1 second
time.sleep(1)
# When the loop finishes (time is up), display a message
# \a is the terminal's alert character that plays a bell sound
print("Time's up! The alarm is ringing! \a")
except ValueError:
# Handle the case where non-numeric input is given (int() fails)
print("Error: Please enter a valid number.")
except KeyboardInterrupt:
# Handle the case where the user interrupts the program with Ctrl+C
print("\nTimer interrupted.")
Next Steps
Now that you can make a timer, why not try making a game to play against the computer next? Using the `random` module to handle random numbers will open up the next level of fun in programming.
➡️ Create a Simple Number Guessing Game in Python (Using random)