2

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

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Don't use parentheses in your while statements. That's a sign of C poisoning. Instead of while (1):, just while 1: or while True:.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.