zaro

How to Set a Timer in Python?

Published in Python Timers 2 mins read

You can set a timer in Python by using the time module and creating a countdown function. Here's a breakdown of how to do it:

Steps to Create a Countdown Timer

  1. Import the time module: This module provides time-related functions, including the sleep() function used to pause execution for a specified duration.

    import time
  2. Get User Input: Ask the user to enter the desired countdown duration in seconds.

    t = int(input("Enter the time in seconds: "))
  3. Create a countdown() Function: This user-defined function will handle the timer logic. It takes the countdown time (t) as an argument.

  4. Implement the Countdown Loop: Use a while loop that continues as long as the time (t) is greater than 0.

    • Inside the loop, print the remaining time.
    • Use the time.sleep(1) function to pause the execution for 1 second (creating the timer effect).
    • Decrement the time variable (t -= 1) in each loop iteration.
    def countdown(t):
        while t:
            mins, secs = divmod(t, 60)
            timer = '{:02d}:{:02d}'.format(mins, secs)
            print(timer, end="\r")
            time.sleep(1)
            t -= 1
    
        print('Time is up!')

Complete Code Example

import time

def countdown(t):
    while t:
        mins, secs = divmod(t, 60)
        timer = '{:02d}:{:02d}'.format(mins, secs)
        print(timer, end="\r")
        time.sleep(1)
        t -= 1

    print('Time is up!')

t = int(input("Enter the time in seconds: "))

countdown(t)

Explanation

  • The code first imports the time module.
  • It then asks the user for the countdown duration in seconds and stores it in variable t.
  • The countdown function uses a while loop that runs until the remaining time, represented by t, is 0.
  • Inside the loop, it calculates the remaining minutes and seconds using divmod() and formats the time into MM:SS format for display.
  • The print(timer, end="\r") ensures that the timer display updates in the same line (using a carriage return).
  • The time.sleep(1) function pauses for 1 second between each loop cycle.
  • The time t is decremented by 1 in each loop cycle.
  • When the timer finishes, it prints the message 'Time is up!'.

This approach provides a basic and effective timer implementation using Python's standard time module.