Python Countdown Timer: Simple Code to Display and Track Time in Real-Time

codepythonic
0


import time

def countdown(time_sec):
    """
    A function that counts down from a specified number of seconds.
    """
    while time_sec:
        mins, secs = divmod(time_sec, 60)
        timeformat = '{:02d}:{:02d}'.format(mins, secs)
        print(timeformat, end='\r')
        time.sleep(1)
        time_sec -= 1
    print("Time Ended")

countdown(100)



Explanation:

  • The countdown function takes a parameter time_sec, which represents the number of seconds to count down from.
  • Inside the function, there is a while loop that continues until time_sec becomes zero.
  • The divmod function is used to calculate the minutes and seconds from the remaining time in seconds.
  • The timeformat variable is formatted to display the time in a two-digit format for minutes and seconds (e.g., "03:45").
  • The print statement displays the formatted time using the carriage return character (\r) to overwrite the previous output.
  • time.sleep(1) pauses the execution for one second, creating a one-second delay between each iteration of the loop.
  • After each iteration, time_sec is decremented by one until it reaches zero.
  • When the loop finishes, the "Time Ended" message is displayed.



Tags:

Post a Comment

0Comments

Post a Comment (0)