0

I have the below code and want to create a countdown clock that counts down from 10 to 9, 8, 7 etc.

I want one number to replace the previous on the same line and same position (i.e. you see one number at any time).

Is there a print method to do that?

I am new to programming and found that os.system('cls') can do the trick but there must be a more eloquent solution?

 import time

    def stopwatch(seconds):
        start = time.time()
        time.clock()    
        elapsed = 0
        while elapsed < seconds:
            elapsed = time.time() - start
            print ("loop cycle time: %f, seconds count: %02d" % (time.clock() , elapsed), end=" ") 
        time.sleep(1)  

    stopwatch(20)
King
  • 3,457
  • 3
  • 12
  • 22
newb
  • 11
  • 4
  • Print a carriage return character at the start of each line ('\r') – rghome Jul 02 '15 at 15:32
  • thanks so much - was googling already for an hour!! – newb Jul 02 '15 at 15:37
  • on another note: is there a way you can print on screen position coordinates. i.e. something like: pos(x,y) - print ("hello") i.e. pos(5,10) would be line 5, pos 10 [hello] – newb Jul 02 '15 at 15:40
  • Thanks - I googled tput but I'm still on windows 7 (not unix) - can you use tput (or its equivalent) in a windows environment? – newb Jul 03 '15 at 00:25
  • I suggest raising another question. Please make clear your environment (Windows), language (Python, I suppose) and where it is run (in a command window?) – rghome Jul 03 '15 at 08:26

1 Answers1

0

You can add printing \r as below :

print ("loop cycle time: %f, seconds count: %02d" % (time.clock() , elapsed), end=" ") 
print ('\r')

Carriage Return takes cursor to the start of line

Amol Saindane
  • 1,568
  • 10
  • 19