Search code examples
pythonfor-loopinputcountdown

Countdown loop for a 'raw_input' on the same line in Python


I want to do a countdown loop for a normal raw_input were the normal raw_input don't change, only the numbers (in raw_input).

So, Do you want to try again? [15-1] outputs on one line and the numbers only change.

This is what I have so far and it doesn't work. So how would I do this?

while True:
            for i in range(15,-1,-1):
                con1=raw_input("\n Do you want to try again? " + str(i,))
            if i == 0:
                print "\n Thanks for playing!"
                exit(0)
            elif con1 == "no":
                print "\n Thanks for playing!"
                time.sleep(3)
                exit(0)
            elif con1 == "yes":
                break

Solution

  • Linux answer -- will not work on Windows

    Python 3

    import select
    import sys
    
    
    def has_input(timeout=0.0):
        return select.select([sys.stdin], [], [], timeout)[0]
    
    
    def getans(timeout=15):
        i = timeout
        max_num_length = len(str(timeout))
        while i:
            print("\rDo you want to try again? {:{}} ".format(i, max_num_length),
                  end="", flush=True)
            i -= 1
            if has_input(1):
                return input()
        print()
        return None
    
    print(getans())
    

    Python 2

    import select
    import sys
    
    
    def has_input(timeout=0.0):
        return select.select([sys.stdin], [], [], timeout)[0]
    
    
    def getans(timeout=15):
        i = timeout
        max_num_length = len(str(timeout))
        while i:
            sys.stdout.write("\rDo you want to try again? {:{}} ".format(i, max_num_length))
            sys.stdout.flush()
            i -= 1
            if has_input(1):
                return raw_input()
        print
        return None
    
    print getans(5)
    

    getans will return None on timeout, or the response otherwise. Theoretically, if a Windows version of has_input could be implemented, this could work on Windows, but I haven't tested that.