[Tutor] Using time module to count-off seconds

Michael Janssen Janssen@rz.uni-frankfurt.de
Wed Jun 18 17:46:47 2003

On Wed, 18 Jun 2003, valhalla wrote:

> Hello
> I am wanting to modify a guessing game script I have so that the player is
> given x number of seconds (e.g. 60 seconds) during which to guess the answer
> before time's up and game is over.

time modul hasn't got a function like that. I believe it's unlikly any
modul ever contains one, because it's easily done and things like "print
to stdout" arn't of general value (for example in GUI programming).

A simple function is:

def countdown(amount):
    for n in range(amount, 0, -1):
        print n

This isn't absolutly accurate, but enough for a 60 sec countdown. The
whole trick is the range function with negative third argument.

You might want to print the countdown on one single line. This can be
done with:
print " %i\033[A" % n

"\033[A" is ANSI for "one line up" (print's newline will then going back
to the line and to its beginning)