如何在循环中忽略输入 [Python]

How to ignore input while in a loop [Python]

我想知道如何忽略 Python 中循环的输入。

下面的代码是一个简单的 Python 代码,它接受数字输入作为循环数字并在循环中打印一个字符。

import time
    
while (1):  # main loop
    x = 0
    inputValue = input("Input a number: ")

    while(x <  int(inputValue)):
        print(x)
        x = x + 1
        time.sleep(1)

但是,当您在循环进行(循环)时从键盘输入内容并按回车键时,此值将成为下一个循环主循环的输入。

我的问题是如何避免这种情况或忽略循环中间的输入。

我试过使用刷新或使用键盘中断,但仍然是同样的问题。

这可能是一个解决方案:

import time
import sys

def flush_input():
    try:
        import msvcrt
        while msvcrt.kbhit():
            msvcrt.getch()
    except ImportError:
        import sys, termios    #for linux/unix
        termios.tcflush(sys.stdin, termios.TCIOFLUSH)

while (1): # main loop
    x = 0
    flush_input()
    inputValue = input("Input a number: ")
    while(x <  int(inputValue)):
        print(x)
        x = x + 1
        time.sleep(1)

归因: Rosetta Code