Step-by-step Coding Tutorial for a Simple Timer in Python

by slucha in Teachers > 4

431 Views, 3 Favorites, 0 Comments

Step-by-step Coding Tutorial for a Simple Timer in Python

pomodoro.png

In this tutorial, we will create a simple console-based timer application using Python. The application will:


1. Prompt the user to enter a duration for the timer in minutes.

2. Convert the user's input from minutes to seconds for the countdown mechanism.

3. Display a countdown timer in the console, updating every second.

4. Notify the user with a message when the timer reaches zero.

5. Handle any interruptions, such as the user pressing `Ctrl+C` to cancel the timer, by displaying a cancellation message.


By the end of this tutorial, you will have a functional timer that can be used for various purposes, such as timing activities or serving as a basic Pomodoro timer for productivity sessions. The tutorial will guide you through setting up your Python environment, writing the script step by step, and running the timer in the Windows console. This is a simple implementation of web based pomodoro timer apps like for example pomodoro timer app (https://pomodorotimerapp.com). With this knowledge, you will be able to understand the logic of a task-based timer and start working your way towards more complex apps like the one mentioned above.

Setting Up Your Environment

python.png


Before you start coding, you need to have Python installed on your computer. You can download and install it from the official Python website: https://www.python.org/downloads/. On Windows it is as simple as downloading the suggested installer and thats it.

Writing the Python Script

ide.png

Open a text editor or an Integrated Development Environment (IDE) like Visual Studio Code, PyCharm, or even Notepad, and get ready to write your Python script. If you dont have this installed you can also use a simple Notepad and then later save the file with the " .py" extension

Importing Modules

module.png

At the top of your script, you need to import the necessary modules. For this timer, you'll need the `time` module to handle the countdown functionality.

Creating the Timer Function

timer.png

You'll create a function called `start_timer` that takes one argument: the duration of the timer in minutes.



def start_timer(duration_in_minutes):
# Convert minutes to seconds
duration_in_seconds = int(duration_in_minutes * 60)

# Countdown loop
try:
for remaining in range(duration_in_seconds, 0, -1):
# Calculate minutes and seconds
mins, secs = divmod(remaining, 60)
# Format the time as MM:SS
timer = '{:02d}:{:02d}'.format(mins, secs)
# Print the timer and overwrite the previous line
print(timer, end="\r")
# Wait for a second
time.sleep(1)
# Notify the user when the timer is up
print("\nTime's up!")
except KeyboardInterrupt:
# Handle the user pressing Ctrl+C
print("\nTimer cancelled.")


Creating the Main Function

main.png

The `main` function will handle user input and start the timer.



def main():
try:
# Ask the user to enter the timer duration
user_input = input("Enter the desired length of the timer in minutes: ")
# Convert the input to a floating-point number
duration_in_minutes = float(user_input)
# Inform the user that the timer is starting
print(f"Timer is set for {duration_in_minutes} minutes.")
# Start the timer
start_timer(duration_in_minutes)
except ValueError:
# Handle invalid input
print("Please enter a valid number.")


Starting the Script

At the bottom of your script, you'll add a conditional statement to ensure that the `main` function runs when the script is executed directly.



if __name__ == "__main__":
main()


Saving the Script

Save your script with a `.py` extension, for example, `timer.py`. If you used a simple textfile instead of an ide make sure to select save as and put the .py extension in double quotes. For example "timer.py" when saving it.

Running the Script

Open the Windows console (Command Prompt or PowerShell), navigate to the directory where you saved `timer.py`, and run the script by typing `python timer.py`.

Using the Timer

pomodoro.png

Enter the desired length of the timer in minutes when prompted, and watch the countdown begin. If you need to stop the timer, press `Ctrl+C`.

Understanding the Code

- The `import time` statement allows you to use the `time.sleep` function to pause the program for a second during each iteration of the countdown loop.

- The `start_timer` function converts the input minutes to seconds, then counts down from that number to zero, updating the console with the remaining time each second.

- The `main` function is where the program starts, prompting the user for input and handling any errors that might occur if the input is not a valid number.

- The `if __name__ == "__main__":` line checks if the script is being run directly (not imported as a module) and if so, it calls the `main` function to start the program.