' raw_input'的倒计时循环在Python的同一行

时间:2014-09-06 14:56:58

标签: python for-loop input countdown

我想对正常raw_input进行正常raw_input的倒计时循环,只更改数字(raw_input)。

所以,你想再试一次吗? [15-1] 在一行输出,数字只会改变。

这是我到目前为止所做的,但它并没有起作用。那我该怎么做呢?

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

1 个答案:

答案 0 :(得分:3)

Linux答案 - 无法在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将在超时时返回None,否则返回响应。从理论上讲,如果可以实现Windows版has_input,这可以在Windows上运行,但我没有测试过。