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
-
Import the
time
module: This module provides time-related functions, including thesleep()
function used to pause execution for a specified duration.import time
-
Get User Input: Ask the user to enter the desired countdown duration in seconds.
t = int(input("Enter the time in seconds: "))
-
Create a
countdown()
Function: This user-defined function will handle the timer logic. It takes the countdown time (t
) as an argument. -
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 awhile
loop that runs until the remaining time, represented byt
, is 0. - Inside the loop, it calculates the remaining minutes and seconds using
divmod()
and formats the time intoMM: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.