Skip to content Skip to sidebar Skip to footer

How To Do Something Till An Input Is Detected In Python3?

I want to execute a piece of code till the user enters an input(detects a random keypress), how do I do that in Python 3.x? Here is the pseudo-code: while input == False: print

Solution 1:

You can do it like this:

try:
    whileTrue:
        print("Running")
except KeyboardInterrupt:
    print("User pressed CTRL+c. Program terminated.")

The user just need to press Control+c.

Python provide the built-in exception KeyboardInterrupt to handle this.

To do it with any random key-press with pynput

import threading
from pynput.keyboard import Key, Listener

classMyClass():def__init__(self) -> None:self.user_press = False

    defRandomPress(self, key):
        self.user_press = True

    defMainProgram(self):
        whileself.user_press == False:
            print("Running")
        print("Key pressed, program stop.")

    defRun(self):
        t1 = threading.Thread(target=self.MainProgram)
        t1.start()

        # Collect events until released
        with Listener(on_press=self.RandomPress) as listener:
            listener.join()

MyClass().Run()

Solution 2:

If you want to interact with users, you may follow the below way:

flag = input("please enter yes or no?")
if flag == "no":
    print(x)

Post a Comment for "How To Do Something Till An Input Is Detected In Python3?"