繁体   English   中英

如何在循环中忽略输入[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)

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

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

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

这可能是一个解决方案:

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)

归属: 罗塞塔密码

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM