-4

I'm building a time count-downter. I just wanted to update the 'time' everytime instead of printing the whole thing again and again. Loops prints the same thing again and again. Like, suppose I want to print 1 to 10. The output will be 1 2 3 4 5 ... But I want 1 (and then the 1 will be removed) 2 ( it will be removed and the next one will be printed)

Aman
  • 11
  • 2

1 Answers1

0

\r prints a carriage return first, so remain_time is printed on top of the previous line.

import sys                #Added
import time              

while True:
  now= time.time()
  current_time= (time.asctime())
  current_hour= current_time[11:13]
  current_minute= current_time[14:16]
  current_second= current_time[17:19]
  remain_hour= 23 - int(current_hour)
  remain_minute= 60 - int(current_minute)
  remain_second= 60 - int(current_second)

  remain_time= "%sh %sm and %ss remaining" %(str(remain_hour),str(remain_minute), str(remain_second))
  sys.stdout.write('\r'+remain_time)                #Changed
  #print('\r'+remain_time,end="")      #Alternatively you can also use this
  time.sleep(1)                                     #Changed
mehrdadep
  • 972
  • 1
  • 15
  • 37