How to ignore input while in a loop [Python]

Viewed 222

I'm trying to figure out how can I ignore input from a loop in Python.

The code below is a simple Python code that accepts numeric input as a number of loop and prints a character in a loop.

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)

However, when you input something from the keyboard and press enter while the loop is ongoing (looping) this value becomes the input to the next loop main loop.

My problem is how can I avoid this or ignore the input in the middle of the loop.

I tried using flush or using the keyboard interrupt but still the same problem.

1 Answers

This may be a solution:

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)

Attribution : Rosetta Code

Related