Search code examples
pythonloopsinput

How to continue running code and still get input from user?


How to continue running code and still get input from user so you can select items from typing while in the terminal as code is being ran.

I tried this code:

itemA = False
itemB = False
itemC = False

while True:
    input = input("input example")

    if input == "a":
        # execute a's code
    # execute code

This only executes the code under input() after input() is ran, and asks the input again.

How can I make this run the code under input without stopping for every input()?


Solution

  • You can use the threading package to do this. This allows you to basically have 2 while loops running at the same time. In your case, one for input and one for other code. Here is some code that will do this.

    itemA = False
    itemB = False
    itemC = False
    import threading
    
    def execute_code():
        while True:
            # execute code (not waiting for input)
            print("hi")
            continue
    threading.Thread(target=execute_code).start()
    
    while True:
        input("input example")
        # execute code (waiting for input)