1

I'm attempting to make a countdown timer starting from 60 seconds. My only problem is that when I run the function, the program prints the code like so:

60

59

58

... etc

How would I go about replacing the 60 from that first line and put the 59 in it's place without printing 60 lines?

Here's my code:

from __future__ import division
import sys, time 

def countdown():
    seconds = 60
    while seconds >= 0:
        print seconds
        sys.stdout.flush()
        time.sleep(1)
        seconds -= 1
Conduit
  • 2,675
  • 1
  • 26
  • 39
  • 1
    Careful with those tags! r is a reference to a language, not /r – Conduit Sep 09 '14 at 20:21
  • @Conduit My apologies. Wasn't paying attention to the tags when adding them. –  Sep 09 '14 at 20:40
  • @Quadufu No worries - learning how to use SO takes a bit of time. Stick with it though! This is one of the best programming resources on the web, IMO. – Conduit Sep 10 '14 at 17:06

1 Answers1

3

Print an empty line at the beginning of your countdown function. This will create the line needed for \r to work. Now, replace the print seconds part with

sys.stdout.write('\r  \r')
sys.stdout.write(str(seconds))

The first line clears the previous, empty line printed at the beginning of the function. The second one outputs the seconds.

The code:

def countdown():
    seconds = 60
    print ''
    while seconds >= 0:
        sys.stdout.write('\r  \r')
        sys.stdout.write(str(seconds))
        sys.stdout.flush()
        time.sleep(1)
        seconds -= 1
Maciej Gol
  • 15,394
  • 4
  • 33
  • 51
  • This worked. However, I don't fully understand why. What does the sys.stdout.write() function do? –  Sep 09 '14 at 20:41
  • `sys.stdout.write` does the same thing as `print`, but it doesn't implicitly add `'\n'` at the end. That's what was messing up your earlier attempts. – Dan Lenski Sep 09 '14 at 23:39